Boost ASIO Simple UDP Send Packet Example

Update: I have written a simple Fire-And-Forget wrapper class for sending datagrams via UDP can be found here. It handles simple transmission use cases while hiding the (sometimes confusing) boost::asio details. However, if you are interested in the details then read on!

Boost.ASIO is great but if you don’t use it everyday it can be hard to remember how to use it to do even the simplest of things. I have included below a sample of simply sending a packet via UDP (ipv4), see the function called send_message(), this example code aims to be as minimal as it can be:

Those spouting software engineering dogma will often tell you to steer well clear of UDP for the usual, well understood reasons, but for a certain type of application where very low latency is important, it just can’t be beat!!

#include 
#include 
using namespace boost::asio;
//
// Send a string via UDP to the specified destination
// ip addresss at the specified port (point-to-point
// not broadcast)
//
bool send_udp_message(const std::string& message, const std::string& destination_ip,
						const unsigned short port) {
	io_service io_service;
	ip::udp::socket socket(io_service);
	// Create the remote endpoint using the destination ip address and
	// the target port number.  This is not a broadcast
	auto remote = ip::udp::endpoint(ip::address::from_string(destination_ip), port);
	try {
	
		// Open the socket, socket's destructor will
		// automatically close it.
		socket.open(boost::asio::ip::udp::v4());
		// And send the string... (synchronous / blocking)
		socket.send_to(buffer(message), remote);
	
	} catch (const boost::system::system_error& ex) {
		// Exception thrown!
		// Examine ex.code() and ex.what() to see what went wrong!
		return false;
	}
	return true;
}

This is the bare-bones code, no error reporting etc. Also it won’t broadcast, to allow for broadcast you need to include the following two lines and supply a broadcast ip address when calling the function. Be careful if broadcasting a lot of data as it can really overload & mess-up network equipment!

socket_base::broadcast option(true);
socket.set_option(option);

Fixed – KDevelop not stopping at breakpoints on Ubuntu Mate

I couldn’t get KDevelop to stop at breakpoints even on simple ‘hello world’ C++ projects. It appeared that CMAKE_BUILD_TYPE was being correctly set and GDB worked fine from the command-line, but from within kdevelop breakpoints were never respected! I think the problem stemmed from the Cache Value for CMAKE_BUILD_TYPE being empty, this value can be seen in the Project / Open Configuration… menu:

kdevelop breakpoint broken

Following the advice from this post I added the following into the project’s CMakeLists.txt file:

# Set a default build type if none was specified
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
  message(STATUS "Setting build type to 'Debug' as none was specified.")
  set(CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build." FORCE)
  # Set the possible values of build type for cmake-gui
  set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release"
    "MinSizeRel" "RelWithDebInfo")
endif()

[Originally from here]

I ran clean & rebuild etc. and then cache value was set correctly to ‘Debug’ and the debugger happily stops at breakpoints!

I hope this post helps folks as I spent _ages_ trying to get the breakpoints to work!!

Bash – send data to serial (rs232) port and wait for response

Sending data to a serial port is quite easy in Bash, for example:
echo "my packet data" > /dev/ttyS0
And you can read from a serial port using cat:  
cat /dev/ttyS0
However cat must typically be run from a different shell instance as it blocks waiting for data. So is it possible to write and then read the response from a single shell instance? Well, it is, but it requires a bit of sleight-of-hand. For example, if we start cat in the background and then send the command, cat will report the response as follows:
# Run cat in the background
cat /dev/ttyS0&
# Send the command, cat should print the response
echo "my packet data" > /dev/ttyS0
Which works but it a bit of a mouth-full! cat continues to run in the background, and will print more responses as they arrive. But what if you want to just send one packet and then wait for a single response? This is a bit harder, but if your response ends with an end of line character, or another known character then we can use read to help with this… First we setup a read command in the background, unlike cat, this command will end when a response is received or when the timeout time arrives, then we can send our command:
(read -n60 -t20 RESP < /dev/ttyS0; echo $RESP)&
echo "my packet data" > /dev/ttyS0
This gets read to wait for up to 20 seconds (-t20) for a line of data (max size, 60 characters -n60) from /dev/ttyS0, which it reads into RESP, it then echos $RESP – all of this happens in the background. echo then sends the packet which will result in a response. If your response packed ends with a character other than an EOL character then you can specify a delimiter to read using the -d command-line option. Again it’s all a bit long winded, so we can wrap it all up in a bash script (send_tty.sh) as follows:
#!/bin/sh
#
# Send a packet to the specified serial port
# and wait for, and output the response, it is assumed
# that the response will end with an EOL character.
#
# usage: send_tty.sh <data-to-send> <port>
#
# [backgound] Wait for, and read a line from the serial port into RESP,
# max 128 characters, timeout=10s, then output $RESP
#
# (c) 2019 Kevin Godden
#
(read -n128 -t10 RESP < $2; echo $RESP)&
# Hack - use read to pause for 200ms to give previous
# command a chance to get started..
read -p "" -t 0.2
# Send command
printf "$1\r" > $2
# Wait for background read to complete
wait
An example of using the script:
./send_tty.sh "my-command" /dev/ttyPS0./send_tty.sh "my-command" /dev/ttyPS0
Github repo is here

PCL C2988 unrecognizable template declaration/definition Visual Studio 2017

If you get this compile error:

Error C2988 unrecognizable template declaration/definition

When you:

#include 

from the Point Cloud Library (PCL) in Visual Studio 2017, then either throw the following in before the #include, like this:

//
#define BOOST_TYPEOF_EMULATION
#include 

or upgrade your version of Visual Studio 2017 (I haven’t tested this yet myself!)

Not sure why, it’s something to do with workarounds for VS 2017 bugs or something…

ExifTool truncates ASCII MakerNote data

ExifTool can be used to output a specific Exif MakerNote from your images’ metadata by using the following command:

exiftool -u -Unknown_0x0013 image.jpg

This will output makernote Id 0x13, however if the makernote that you are interested is long, then ExifTool may truncate it and output only the start with […] at the end!

Unknown 0x0013                  : {"distortion":{"factory":{"version":"1.0","medium":"air[...]

To have ExifTool output the full makernote, use the -b (binary) option like this:

exiftool -u -b -Unknown_0x0013 image.jpg

Raspberry Pi and GPS for Testing Camera Image Timestamps with NTP and PPS

raspberry_pi_gps_pps_time_image_timestamp

An image time-stamp will tell you when an image was acquired by its camera, they are typically donated in Coordinated Universal Time (UTC) – accurate time-stamps are very often important in Computer Vision Applications especially those that involve observing or analyzing change over time.

Implementing such time-stamp functionality on a camera is very hard and typically involves both hardware and software support – testing the functionality to make sure that the time-stamps are accurate is nearly even harder!

A time-stamp’s accuracy is partly dependent on how well the camera’s time is synchronized, if it’s time is well synchronized by the Network Time Protocol (NTP) then an accuracy of a few milliseconds can be expected, if full pulse-per-second (PPS) synchronization is used then (with care) an accuracy of tens of microseconds can be achieved.

In order to test time-stamp accuracy it is necessary to have an accurate time source to act as a test base-line for comparison purposes, multiple cameras can the then be synchronized to this via their acquisition triggers and NTP or PPS and their images and image time-stamps can be compared.

To this end we have been prototyping a Stratum 1 time source built using a Raspberry Pi with a GPS shield. This will take its time reference from GPS and provide the following for testing cameras:

+ NTP time server (stratum 1) – Raspberry Pi & NTP syncs its time to GPS time via PPS signal and time packets (ZDA packets), the cameras’ NTP clients can use this for synchronizing their clocks (purley software based synchronization).

+ Electrical PPS output – Can be used by camera for syncing it’s time via PPS and for triggering acquisition on second boundaries

+ Re-transmit PPS time packets (ZDA) via UDP – Can be used by cameras for syncing their time via PPS (software & hardware synchronization)

To build the time source we are following this excellent article which explains the various steps involved:

http://www.satsignal.eu/ntp/Raspberry-Pi-NTP.html

Many thanks to David Taylor, it is a rather complex subject with lots of software setup on the Pi, it hurts our heads but we are making progress, and the initial prototype has already been very helpful in characterizing camera triggering and time-stamping behavior. We expect great things.

In terms of hardware we are using:

Uptronics Raspberry Pi+ GPS Expansion Board – with the GPS Timing Antenna

Raspberry Pi 3

Image Processing with Intel’s SSE SIMD instructions for 12-bit images

Over the last few days I have been working on implementing some low-level 12-bit image processing functions using Intel’s SIMD instruction set – SSE. The aim here is to increase processing time performance as much as possible – initial results are very encouraging, those 128bit register really get things to scream along!

It has been a while since I have done such work on Intel devices (ARM and hence ARM NEON is more common on IoT projects), the last time was before MMX ‘Intrinsics’ were invented and involved hand coding MMX instructions with associated support assembly language. Intrinsics really make coding this stuff so much simpler!

Very often it doesn’t pay for a software engineer to hand-code and optimise image processing algorithms, but when maximum performance is required, huge speed gains can be made with some careful coding on standard hardware!

Accuracy of the various Windows software timers

This (admittedly quite old) article provides an interesting comparison of the accuracy of the various software timers available under windows, it looks like the Multimedia timers are still the best despite apparently being frowned upon my Microsoft.

http://omeg.pl/blog/2011/11/on-winapi-timers-and-their-resolution/

I plan to trial camera acquisition using a software trigger, and in order to obtain as accurate and reliable a trigger as possible I want to get as close to a timer interrupt handler as windows will allow, in the hopes that it will be ‘good enough’ for my computer vision application. For a really reliable trigger time-base I normally use a hardware trigger generated by a micro-controller or similar, but this time as the timing constraints aren’t as onerous I have decided to see if I can get away without one, so we will see…. I guess I will have to test the various options and see which is best and if any of them are (generally) within spec..

Good NTP Client Setup Description

As a software engineer (rather than an NTP guru), I find that configuring and debugging an NTP setup can be quite challenging, it is (by its nature) a difficult subject, and a lot of the info out there is quite dense and hard to parse, so I was presently surprised to come across this nice article, called ‘Real Life NTP’ which gives a good overview and describes the use of ntpq -p etc.

https://pthree.org/2013/11/05/real-life-ntp/

Thanks Aaron!

Nice Bootsrap / AngularJS based templates

I was browsing yesterday and came across some nice bootstrap based templates for web app development, especially this one:

http://wrapbootstrap.com/preview/WB04HF123

The nice this is that a version built on AngularJS is available, although I can’t vouch for its build quality not having seen the code…

Templates like these are a great starting point for software developers wishing to put together a web application that doesn’t necessarily look terrible – without the need of one of those GUI guys! Perfect for developing a HMI for an embedded device for example or for developing a cloud application, or even for developing a local app on your PC with Node.js!?