Broadcast TCP-Server with libevent - tcp

I am looking for some sample code of a dead simple libevent-based TCP-Server which broadcasts incoming Messages to all connected clients. On the Web I only found TCP-Servers which echoes back messages.
One echo example if found is on the bottom of this page http://www.wangafu.net/~nickm/libevent-book/Ref8_listener.html
I am sure that its not so difficult to change the code provided on this Site, so that messages are brodcast to all connected clients, but I don't know how.
Could someone advise me?
EDIT: Yes, some kind of a chat server. It seams i need to do sth like this:
void server_read_cb(struct bufferevent *bev, void *data)
{
struct evbuffer *input = bufferevent_get_input(bev);
struct evbuffer *output = bufferevent_get_output(bev);
char *mem = malloc(len); /* XXX: check for malloc failure */
evbuffer_remove(input, mem, len);
"for every connection conn" {
/* XXX you'll need to implement a real connection list;
the above isn't real C. */
evbuffer_add(bufferevent_get_output(conn), mem, len);
}
free(mem);
}
But i can't put this to work.

Seems you want something similar to a chat server. One example is here. Basically, when you receive data from one connection, you just go through the list of connections and send that same data to each one (including/excluding the original).

Related

Establishing serial port communication between Arduino and Godot?

I’m wondering how do I go about establishing a serial port communication between Arduino Uno (as my input) and Godot game engine (as my output)? Context is, I'm trying to use sensors on Arduino to move/place objects on Godot, thus I need the serial port code or guidance on how to go about achieving that connection.
Any help is appreciated, thank you everyone!
You can try plugin GDSerCommPlugin. But it is work in progress and i didnt test it so i dont know if it is usable.
Since it's a long time this question was asked, I think that an update is welcome.
Since Godot 3.0, C# is fully supported, I'm using Godot 3.3.2 and my conclusion about dealing with serial communication in Godot is : use C#
You'll keep all the multi platform development advantage of Godot without writing a single (low level) line of code, here is a snipped:
using System.IO.Ports; // for .NET SerialPort
Then in your class if you want to open the port (assuming "SerialPort port" is defined):
port = new SerialPort(portName, (Int32)baudRate, Parity.None, 8, StopBits.One);
Then use the _Process to read the data:
public override void _Process(float delta)
{
if (port != null)
{
if (port.BytesToRead > 0)
{
string serData = port.ReadExisting();
string[] str = serData.Split('\n'); // Just an example
parseLines(str); // Your implementation
}
}
}
Note1: "DataReceived" event from SerialPort doesn't work (I don't know why but I think this is due to the different context) but with Godot this function is useless since you can check and parse directly the data in the _Process function.
Note2: For efficiency it's better to use the ReadExisting() function (and parse lines yourself) than the Readline() function in a loop in the _Process function.
Note3: Sending to serial port is immediate eg:
port.Write("Hello\r");

Good Practice to pass arguments in queued connection

I want an simple and clear example of how to do the signal and slot mechanism in queued connection.
Take the below line as example. Think that obj1 is backend functionality object emitting signal asynchronously from another thread and is connected to a slot in GUI ( main thread):
connect(obj1, SIGNAL(Mysignal(vector<mystruct> )), this, slot(myslot(vector <mystruct>)))
I have read that you have to register the types(meta types).
Please give a clear, simple and ready to use code lines for the above example that I would need, so that errors during run time like vector, my struct or string not defined, etc.. I don't face.
Also, is there a better way to handle this like sending pointers like:
connect(obj1, SIGNAL(Mysignal(obj2 *)), this, slot(myslot(obj2 *)))
Obj2 contains the vector of mystruct. Will i still need to register the obj2 with those metatypes?
If somebody has experience in this, please share all your good practices and simple code snippets, I am new to the queued connections with arguments. Please help.
If you want a queued connection, you need to call connect with a 5. parameter Qt::QueuedConnection. Otherwise, you get a direct connection inside the thread where you sent the signal from. Edit: See Tobys comment below.
You must wrap a QVector<> into a typedef, otherwise registering will not work (bug? in Qt from the stoneage). Also do not use references to your typedef, will not work either.
Header
typedef struct {
int a;
int b;
} mystruct;
typedef QVector<mystruct> myvector;
Q_DECLARE_METATYPE(myvector);
Source
void MainWindow::test()
{
qRegisterMetaType<myvector>();
connect(this, SIGNAL(sigRec(myvector)), SLOT(slotRec(myvector)), Qt::QueuedConnection);
mystruct x = {1,2};
myvector v;
v.append(x);
emit sigRec(v);
}
void MainWindow::slotRec(myvector s)
{
}

Handling COM serial port communication

I was thinking about a best approach to properly handle the serial port communication in my program. I have some device that sends me data, im reciving it using DataRecieved event and ReadExisting method in it. Everything that it reads is being put inside a buffer, when last line equals some string then i start to parse it into some kind of packet.
Aside from that, when i send data to this device and wait for response, i mark flag
bool isReady = false;
while(!isReady)
Thread.Sleep(500);
And in data parsing method i set this flag to true so when I recieve packet data, code can jump out of this loop and continue to work as needed. But in my opinion this is not a clean/good way to do this. And there is a problem sometimes, if device will not send the packet I need, so program is being stuck in the loop forever.
I was wondering, how would you guys resolve this case in your code?
Thanks, and sorry for bad english.
Don't just wait for a response in an endless loop. Use the events like you previously mentioned to get the data. See this other SO question also. SerialPort class and DataReceived event... Getting bytes. Use ReadLine or ReadExisting? Any examples?
For now i've added a 5sec timeout using following code:
bool isReady = false;
DateTime timeout = DateTime.Now;
while(!isReady)
{
Thread.Sleep(500);
if((DateTime.Now-timeout).TotalMiliseconds >= 5000)
break;
}
So when no response is recieved then it just jumps out of this loop. This is solving one of my problems, but still I would like to know other ways to handle this. If you guys have any ideas, please share them.

Qt5 QSerialPort write data

How I can write data in serial port, with delay between send's messages?
This is my code:
void MainWindow::on_pushButton_Done_clicked()
{
if(sport->isOpen()){
sport->clear();
QString cmd = Phase+Mode;
//Write Stop
sport->write("stop!", 5);
//Write Mode
sport->write(cmd.toStdString().c_str(), cmd.toStdString().length());
//Write Speed
sport->write(Speed.toStdString().c_str(), Speed.toStdString().length());
//Write Direction
sport->write(Direction.toStdString().c_str(), Direction.toStdString().length());
//Run
sport->write("start!", 6);
}
}
My device receives an error message when I call this function.
Thank you.
2 options:
use waitForBytesWritten to ensure the bytes are written and then a short sleep
however this will block the thread and will block the gui
the other is using a QTimer to trigger another slot a few times and a field that will indicate what needs to be sent
Looks like you are trying to program some step motor controller or something similar.
Usually in such controllers you should wait for controller response to verify that command was processed properly.
It looks like that your design of code is very bad. Move everything related with this controller to separate class, which has set of slots, something like: starRotateLeftWithSpeed(double). Code will be cleaner and it will be easy to use thread if you decide to use methods like waitForBytesWritten proposed in another answer.
Definitely you should read controller manual more carefully.

Serial communication in second thread, asynchronously?

I want to put the serial communication with an external device to a second thread, c#.
Here there is my first thread doing some stuff.
And there is the serial worker, the second thread:
It opens the serial port
It asks the external serial device regulary: Are you alive?
It receives queries from the first thread with a string and an int like: "Command2", 33 and it should give this to the external serial device.
Sometimes there comes an answer from the external serial device back with a string and an int like: "Command4", 55 and the second thread should give this to the first thread and it should start a process there.
The second thread also does own things like error detection which I want to keep free the first thread of.
Serial communication itself works fine but I have problems with threads, delegates, BeginInvokes, EventHandlers, etc.
My first thread:
Class MainProgramme
{
internal void StartSerialCommunication
{
=> Here I want the second thread to open the serial port and I want to start the regulary serial device check, all in the
second thread.
}
internal bool SerialCommand(string s, int i)
{
=> Here I want to give the command s and i to the second thread asynchronously. That means this process does not wait for an answer from the second thread.
}
The following process should be fired by the second thread because the second thread has received some important data
from the external serial device.
internal void SerialAnswered
{
=> Here I want to get the string and the int from the second device back.
}
}
My second thread:
Class SerialCommunication
{
internal bool SerialDeviceIsAlive = true;
public bool SerialOpen
{
SerialPortMsp.Open();
RegularyDeviceCheckTimer.Enabled = true;
return true;
}
private void RegularyDeviceCheckTimer_Tick(System.Object
sender, System.EventArgs e)
{
if SerialDeviceIsAlive == true)
{
SerialDeviceIsAlive == false;
}
else
{
=> Here I want to inform the first thread that the answer from the external serial device is missing.
}
SerialSend("AreYouAlive");
}
public void SerialReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
IAmAlive = true;
int buff = SerialPortMsp.ReadExisting();
if (buff.IndexOf(new string('\n', 1)) > 0)
{
=> Here I want to inform the first thread that the answer was buff.
}
}
public bool SerialSend(string SerialCommand)
{
SerialPortMsp.Write(SerialCommand.ToCharArray(), 0,
SerialCommand.Length);
return true;
}
}
I need help in calling processes and transferring data between the two threads.
I think both thread1 and thread2 have their "own" execution path, and you can not force them to "interrupt" and do something with the data that you built in the other thread.
What you can do is that you "plan" for the possibility that there is something ready in the other thread that might need your attention in the current thread. Hence, both thread1 and thread2 need a code that regularly checks if there is something "ready" in the other thread.
If you plan to do other things in thread1 you still need to build in a regular check/poll for the results of thread2 and vica versa.
The concrete communication between the threads might be implemented with a queue in each direction. In .NET 4.0 there is a ConcurrentQueue class for thread-safe producer/consumer implementation. When thread1 has a command it should queue it in the command queue, while thread2 should regularly check if there are commands waiting. When thread2 has a result ready, it should queue it in a result queue, while thread1 should regularly check if there is a result and run the processing code accordingly.
Having all this said, I think you should consider once more, if your solution with exactly these two threads is really what you need. However, this depends on the details of your requirements (e.g. what other things thread1 should do in the meanwhile, and what the processing of the command result means, can it run parallel, etc).
My suggestion would be to align your design based on the producer/consumer pattern. That is a typical concurrency task and you will find a lot of explanations and optimized solutions (e.g. where the consumer does not have to poll the queue, but it can sleep on a waithandle, semaphore, or some other construct without using CPU and it can be waken up by the producers if there is something to consume).
In your case you could use this pattern twice. The CommandProducer is the entity that creates the commands and feeds the CommandConsumer (that can consume it by passing it to the serial line). On the back way you have the CommandResultProducer that reads the serial line and passes the result to the CommandResultConsumer to do something with the result. Aligning your code like this would result in a more flexible and clear solution, and you can even increase the number of consumer or producer threads if it turns out to be practical.

Resources