A C++ program to generate json output

In this post, constructing and printing of JSON output using rapidjson library has been discussed.
For instance, we have a file (probe.json) containing the following json output –

{ MTConnectDevices:
{ attrs:
{ 'xmlns:m': 'urn:mtconnect.org:MTConnectDevices:1.2',
xmlns: 'urn:mtconnect.org:MTConnectDevices:1.2',
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation': 'urn:mtconnect.org:MTConnectDevices:1.2 http://www.mtconnect.org/schemas/MTConnectDevices_1.2.xsd' },
Header:
[ { attrs:
{ creationTime: '2014-09-16T01:01:01Z',
sender: 'vimana',
instanceId: '001',
version: '1.2.0.23',
assetBufferSize: '1024',
assetCount: '0',
bufferSize: '524288' } } ],
Devices:
[ { Device:
[ { attrs: { id: 'DEVICE_01', name: 'Device 01', uuid: 'DEVICE-01' },
Description:
[ { charValue: 'DEVICE_01, DEVICE-01',
attrs: { manufacturer: 'Manufacturer-01' } } ] } ] } ] } }

A c++ code for this may be written in the following manner-

#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include<iostream>

using namespace rapidjson;

int main()
{
const char* probe=”{ \”MTConnectDevices\”:\n{ \”attrs\”:\n{ \”xmlns:m\”: \”urn:mtconnect.org:MTConnectDevices:1.2\”,\”xmlns\”: \”urn:mtconnect. org:MTConnectDevices:1.2\”,\”xmlns:xsi\”: \”http://www.w3.org/2001/XMLSchema-instance\”,\”xsi:schemaLocation\”: \”urn:mtconnect.org:MTConnectDevice s:1.2 http://www.mtconnect.org/schemas/MTConnectDevices_1.2.xsd\” },\n\”Header\”:\n[ { \”attrs\”:\n{ \”creationTime\”: \”2014-09-16T01:01:01Z\”,\n\ “sender\”:\n \”vimana\”,\n\”instanceId\”: \”001\”,\n\”version\”: \”1.2.0.23\”,\n\”assetBufferSize\”:\”1024\”,\n\”assetCount\”: \”0\”,\n\”bufferSize \”: \”524288\” } } ],\n\”Devices\”:\n[ { \”Device\”:\n[ { \”attrs\”: { \”id\”: \”DEVICE_01\”, \”name\”: \”Device 01\”, \”uuid\”: \”DEVICE-01\” },\n \”Description\”:\n[ { \”charValue\”: \”DEVICE_01, DEVICE-01\”,\n\”attrs\”: { \”manufacturer\”: \”Manufacturer-01\” } } ] } ] } ] }}”;

Document d;
d.Parse(probe);
printf(“PROBE :\n %s \n”,probe);

}

Compilation of the code can be done by –
g++ probe.cpp
On success,type
./a.out

the output obtained is –

PROBE :
{ "MTConnectDevices":
{ "attrs":
{ "xmlns:m": "urn:mtconnect.org:MTConnectDevices:1.2","xmlns": "urn:mtconnect.org:MTConnectDevices:1.2","xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance","xsi:schemaLocation": "urn:mtconnect.org:MTConnectDevices:1.2 http://www.mtconnect.org/schemas/MTConnectDevices_1.2.xsd" },
"Header":
[ { "attrs":
{ "creationTime": "2014-09-16T01:01:01Z",
"sender":
"vimana",
"instanceId": "001",
"version": "1.2.0.23",
"assetBufferSize":"1024",
"assetCount": "0",
"bufferSize": "524288" } } ],
"Devices":
[ { "Device":
[ { "attrs": { "id": "DEVICE_01", "name": "Device 01", "uuid": "DEVICE-01" },
"Description":
[ { "charValue": "DEVICE_01, DEVICE-01",
"attrs": { "manufacturer": "Manufacturer-01" } } ] } ] } ] }}

(This .cpp file should be present in the sub-folder ../rapidjson/include . My previous post can be referred for information on rapidjson folder)

Standalone C++ program to create the JSON for one XML output using rapidjson.

pallavichaurasia94

Rapidjson is a C++ JSON parser and generator. In other words, it helps a C++ program to read JSON data and write JSON data.
rapidjson supports SAX (Simple API for XML) style and DOM (Document Object Model) for parsing.

Installation
(rapidjson is a header-only library. That means, the only thing to be done is to copy rapidjson/include/rapidjson and its sub-directories to your project or other include paths.)
the steps mentioned below are for the Mint distribution-

The rapidjson package can be downloaded from here – http://code.google.com/p/rapidjson/downloads/list . It can then be unpacked.
(considering that the folder containing the installed rapidjson is ‘rapidjson’)

before proceeding, certain libraries need to be installed, which can be done by-
$sudo apt-get install gcc-multilib g++-multilib

now, run GNU make in build/gmake,(inside ‘rapidjson’) for example-
$make -f test.make config=release32
$make -f example.make config=debug32

On success, the executable are generated at rapidjson/bin

inside the ‘include’ sub-folder (in…

View original post 118 more words

Standalone C++ program to create the JSON for one XML output using rapidjson.

Rapidjson is a C++ JSON parser and generator. In other words, it helps a C++ program to read JSON data and write JSON data.
rapidjson supports SAX (Simple API for XML) style and DOM (Document Object Model) for parsing.

Installation
(rapidjson is a header-only library. That means, the only thing to be done is to copy rapidjson/include/rapidjson and its sub-directories to your project or other include paths.)
the steps mentioned below are for the Mint distribution-

The rapidjson package can be downloaded from here – http://code.google.com/p/rapidjson/downloads/list . It can then be unpacked.
(considering that the folder containing the installed rapidjson is ‘rapidjson’)

before proceeding, certain libraries need to be installed, which can be done by-
$sudo apt-get install gcc-multilib g++-multilib

now, run GNU make in build/gmake,(inside ‘rapidjson’) for example-
$make -f test.make config=release32
$make -f example.make config=debug32

On success, the executable are generated at rapidjson/bin

inside the ‘include’ sub-folder (in rapidjson), a file (let’s say, prog1.cpp) containing the following c++ code is to be added –

#include "rapidjson/document.h"
#include

int main() {
const char json[] = “{ \”hello\” : \”world\” }”;

rapidjson::Document d;
d.Parse(json);

printf(“%s\n”, d[“hello”].GetString());

return 0;
}
(the document.h header file can be found inside ‘rapidjson/include/rapidjson’)

In order to compile this code, on the terminal type the command-
$g++ test1.cpp
Once the code has been successfully compiled without any errors, the executables for the same can be created using-
$./a.out
which gives the output –
world

This example parses a JSON text string into a DOM tree. Then it obtains the “hello” member of the root JSON object. Finally it obtains the string of that value, which is “world”.

Testing Paho Python Client in Debian

Here I have discussed how to subscribe to/publish a message via MQTT using a code (the code being written in python language). We would be working with the mosquitto broker. The installation, setup and testing of the mosquitto in debian have been stated in my previous blog Mosquitto in Debian

To achieve the above mentioned goal, testing of Paho Python Client has been briefly described.
The Paho project consists of a number of clients and utilities for working with MQTT. The Paho Python Client provides a client class and some helper functions to make publishing messages to an MQTT server very straightforward.

The Python client can be downloaded and installed from the repository using the following commands-

git clone http://git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.python.git
cd org.eclipse.paho.mqtt.python.git
sudo python setup.py install

Now, in the containing folder, create a file and copy-paste the python code given below which will help subscribe to a certain topic , for e.g., in this case it is “hello/world” –

import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))

# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("hello/world")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+” “+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect(“localhost”, 1883, 60)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()

Compiling this code, starts the client and the following output is obtained –

Connected with result code 0

Open another terminal and create a file containing the following code –

import mosquitto
mqttc = mosquitto.Mosquitto("python_pub")
mqttc.will_set("/event/dropped", "Sorry, I seem to have died.")
mqttc.connect("127.0.0.1", 1883, 60, True)

mqttc.publish("hello/world", "Hello, World!:this works now!!:D")

Each time this piece of code is compiled, something of this sort is displayed in the previous terminal (i.e., from where we started the client) –

hello/world Hello, World!:this works now!!:D

This means that the message ” hello/world Hello, World!:this works now!!:D ” is pushed to all the clients that subscribed to the topic “hello/world”.

Mosquitto in Debian

What is MQTT ?

As the Wiki describes it, MQTT (formerly Message Queue Telemetry Transport) is a publish-subscribe based “light weight” messaging protocol for use on top of the TCP/IP protocol.
With the internet having survived using HTTP for the past several years, a question may arise , why another protocol at all ? Well, the answer may be found here.

In spite of being great in matters where a client wants to make a request to a server and get an answer, HTTP doesn’t prove to be a great solution when a source of information should push a change to a number of clients; also there is not built-in support for quality of service in this case. The text based format of HTTP requires more bandwidth and any device acting as a host needs a web server installed. Running a web server to cater to incoming requests obviously consumes hell lot of battery power.

A great way to overcome these drawbacks is to use MQTT. MQTT uses publish and subscribe messaging pattern wherein any source of information (for e.g. a sensor)can publish its data to which any client can be subscribed. A broker keeps track of these publications and subscriptions. So whenever a publisher sends some new data, he publishes a message and the broker takes care of sending the new data to all subscribers. Hence the broker can guarantee the delivery of a message which is why it is said that MQTT is backed by quality of service. It requires less bandwidth (because of its binary format), has small implementation footprint that requires less battery. MQTT is standardized by OASIS and backed by IBM.

To get familiar with the working of MQTT, we need to set up an MQTT broker and in this post , I have selected ‘mosquitto‘ which is the most famous open source MQTT broker. A quick installation and steps for setting it up in Debian have been discussed below.

Installing Mosquitto

Installing mosquitto in Debian is a simple task. Open a terminal and paste the following commands
(using the new repository with the latest version of the broker is suggested)
To use the new repository, first the repository package signing key should be imported:

wget http://repo.mosquitto.org/debian/mosquitto-repo.gpg.key
sudo apt-key add mosquitto-repo.gpg.key

Then make the repository available to apt:

cd /etc/apt/sources.list.d/
sudo wget http://repo.mosquitto.org/debian/mosquitto-stable.list

Then update apt information:

sudo apt-get update

Finally install:

sudo apt-get install mosquitto

Along-with this, also install,a couple of command line clients for testing your installation:

sudo apt-get install mosquitto-clients

Starting Mosquitto

In order to start the broker , type the following command in your terminal:

sudo /etc/init.d/mosquitto start

To check the status of the broker, give this command:

sudo /etc/init.d/mosquitto status

Or, check the output of :

netstat -na | grep 1883

1883 is the default mosquito server port.

Testing Mosquitto

Subscribing to a topic –
The broker should be up and running on port 1883, assuming that nothing else was running on that port. It can be found out if it is running when the following tests are exectuted. Open 2 terminals. In the first run this command:

mosquitto_sub -d -t hello/world

Here we are subscribing to all messages with the topic “hello/world”

Publishing under a Topic-
To publish a message under a specific topic the following command can be run in the 2nd terminal:

mosquitto_pub -d -t hello/world -m "Hello, MQTT. This is my first message."

This command should have published a message that will be pushed to all clients which have subscribed to the “hello/world” topic.
For e.g. in the case considered, the above command should invoke an output as below in the 1st terminal :
Client mosqsub/12826-cherry sending PINGREQ
Client mosqsub/12826-cherry received PINGRESP
Client mosqsub/12826-cherry received PUBLISH (d0, q0, r0, m0, 'hello/world', ... (38 bytes))
Hello, MQTT. This is my first message.

i.e., the message “Hello, MQTT. This is my first message.” has been pushed to all clients that subscribed to the topic “hello/world”.