Brief:
Basic ESP32 COAP Example
- 
ESp32 wifi module uses provided SSID and password, tries to connect wifi.once connected to wifi, ipadress and SSID is printed on serial monitor.
- Client sends request to controla state of led i.e Status of led to turn ON or OFF the led
- Server upon reciving request, turn ON/OFF led and response the state of led.
Source Code:
/*-------------------------------------------------------------------------------------------------------------------
 * Author          : Emertxe (http://www.emertxe.com) 
 * Date            : Fri 13 Agust  2021 16:00:04 IST
 * File            : esp32_coap.ino
 * Title           : Program on demonstrating COAP based server client communication 
 * Description     : Basic ESP32 COAP example
 *                   ESp32 wifi module uses provided SSID and password, tries to connect wifi.once connected to wifi,
 *                   ipadress and SSID is printed on serial monitor.
 *                   Client sends request to controla state of led i.e Status of led to turn ON or OFF the led
 *                   Server upon reciving request, turn ON/OFF led and response the state of led. 
 * Installation    : Libraries to be installed:
 *                   goto Tools -> Manage Libraries -> search for COAP_simple_libray and install COAP_simple_library
 * Execution Steps : if you change LED, req/res test with coap-client(libcoap), run following.
 *                   coap-client -m get coap://(arduino ip addr)/light
 *                   coap-client -e 1 -m put coap://(arduino ip addr)/light
 *                   coap-client -e 0 -m put coap://(arduino ip addr)/light
 *------------------------------------------------------------------------------------------------------------------*/
#include <WiFi.h>
#include <WiFiUdp.h>
#include <coap-simple.h>
const char* ssid = "*****";
const char* password = "******";
// CoAP client response callback
void callback_response(CoapPacket &packet, IPAddress ip, int port);
// CoAP server endpoint url callback
void callback_light(CoapPacket &packet, IPAddress ip, int port);
// UDP and CoAP class
WiFiUDP udp;
Coap coap(udp);
// LED STATE
bool LEDSTATE;
int led = LED_BUILTIN;
// CoAP server endpoint URL
void callback_light(CoapPacket &packet, IPAddress ip, int port) {
  Serial.println("[Light] ON/OFF");
  
  // send response
  char p[packet.payloadlen + 1];
  memcpy(p, packet.payload, packet.payloadlen);
  p[packet.payloadlen] = NULL;
  
  String message(p);
  if (message.equals("0"))
    LEDSTATE = false;
  else if(message.equals("1"))
    LEDSTATE = true;
      
  if (LEDSTATE) {
    digitalWrite(led, HIGH) ; 
    coap.sendResponse(ip, port, packet.messageid, "1");
  } else { 
    digitalWrite(led, LOW) ; 
    coap.sendResponse(ip, port, packet.messageid, "0");
  }
}
// CoAP client response callback
void callback_response(CoapPacket &packet, IPAddress ip, int port) {
  Serial.println("[Coap Response got]");
  
  char p[packet.payloadlen + 1];
  memcpy(p, packet.payload, packet.payloadlen);
  p[packet.payloadlen] = NULL;
  
  Serial.println(p);
}
void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  // LED State
  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH);
  LEDSTATE = true;
  
  
  Serial.println("Setup Callback Light");
  coap.server(callback_light, "light");
  // client response callback.
  // this endpoint is single callback.
  Serial.println("Setup Response Callback");
  coap.response(callback_response);
  // start coap server/client
  coap.start();
}
void loop() {
  delay(1000);
  coap.loop();
}Raspberry pi sample program output:
Brief:
- ESp32 Wi-Fi module uses provided SSID and password, tries to connect Wi-Fi. Once connected to Wi-Fi ipadress and SSID is printed on serial monitor.
- Browser will act like client.
- ESP32 act as server, server responds with “hello from esp2866” on receiving request for connection.
Source Code:
/*---------------------------------------------------------------------------------------------------------------------------
*Author          : Emertxe (http://www.emertxe.com) 
*Date            : Fri 13 Agust  2021 16:00:04 IST
*File            : HelloServer.ino
*Title           : Program on demonstrating HTTP based server client communication 
*Description     : ESp32 wifi module uses provided SSID and password, tries to connect wifi.once connected to wifi,ipadress
*                  and SSID is printed on serial monitor.Browser will act like client.ESP32 act as server, server responds 
*                  with "hello from esp2866" on reciving rrequest for connection. 
*Installation    : Libraries to be installed:
*                  New version of arduino has all library installed.
*Execution Steps : Copy ip adress from serial terminal.
*                  Paste ip adress on the browser(to get hello from server). 
*----------------------------------------------------------------------------------------------------------------------------*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
const char* ssid = "****";
const char* password = "*****";
// TCP server at port 80 will respond to HTTP requests
WebServer server(80);
const int led = LED_BUILTIN;
//response "hello sserver upon connection"
void handleRoot() 
{
  digitalWrite(led, 1);
  server.send(200, "text/plain", "hello from esp8266!");
  digitalWrite(led, 0);
}
// handle request if path arguments are not matching
void handleNotFound() 
{
  digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++)
  {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
  digitalWrite(led, 0);
}
void setup(void) 
{
  pinMode(led, OUTPUT);
  digitalWrite(led, 0);
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.print(".");
  }
  //once connected to wifi print ipadress
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  if (MDNS.begin("esp32")) 
  {
    Serial.println("MDNS responder started");
  }
  server.on("/", handleRoot);
  server.on("/inline", []() 
  {
    server.send(200, "text/plain", "this works as well");
  });
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.println("HTTP server started");
}
void loop(void) 
{
  server.handleClient();
}Example output:
Brief:
- ESp32 Wi-Fi module uses provided SSID and password, tries to connect Wi-Fi. Once connected to wi-fi, ipadress and SSID is printed on serial monitor.
- Browser will act like client.
- Server responds with turning ON and OFF LED on receiving request ON or OFF as path arguments from client.
Source Code:
/*-----------------------------------------------------------------------------------------------------------------------------
*Author            : Emertxe (http://www.emertxe.com) 
*Date              : Fri 13 Agust  2021 16:00:04 IST
*File              : HelloServer.ino
*Title             : Program on demonstrating HTTP based server client communication 
*Description       : Basic ESP32 HTTP example
*                    ESp32 wifi module uses provided SSID and password, tries to connect wifi.once connected to wifi,
*                    ipadress and SSID is printed on serial monitor.
*                    Browser will act like client.
*                    ESP32 act as server, server responds with "hello from esp2866" on reciving rrequest for connection. 
*                    Server responds with turning ON and OFF led, on reciving request ON or OFF as path arguments from client.
*Istallation       : Libraries to be installed:
*                    New version of arduino has all library installed
*Execution steps   : Copy ip adress from serial terminal.
*                    Paste ip adress on the browser(to get hello from server). 
*                    Paste ip adreess/led/ON or OFF (to control led status on esp32)
------------------------------------------------------------------------------------------------------------------------------*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>
const char* ssid = "***";
const char* password = "***";
// TCP server at port 80 will respond to HTTP requests
WebServer server(80);
void setup(void) {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");
  pinMode(LED_BUILTIN, OUTPUT);
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
//multicast domain name system
  if (MDNS.begin("esp32")) {
    Serial.println("MDNS responder started");
  }
  server.on("/", []() {
    server.send(200, "text/plain", "hello from esp32!");
  });
// to obtain led status from request path agruments
  server.on("/led/{}", []() {
    String led_status = server.pathArg(0);
    int status = led_status == "ON" ? 1 : 0;
    digitalWrite(LED_BUILTIN, status);
    
    server.send(200, "text/plain", "LED: '" + led_status + "'");
  });
  
  server.on("/users/{}", []() {
    String user = server.pathArg(0);
    server.send(200, "text/plain", "User: '" + user + "'");
  });
  
  server.on("/users/{}/devices/{}", []() {
    String user = server.pathArg(0);
    String device = server.pathArg(1);
    server.send(200, "text/plain", "User: '" + user + "' and Device: '" + device + "'");
  });
  server.begin();
  Serial.println("HTTP server started");
}
void loop(void) 
{
  server.handleClient();
}Raspberry pi sample program output:
Brief:
-  It connects to an MQTT server then:
- publishes “hello world” to the topic “outTopic” every two seconds
- subscribes to the topic “inTopic”, printing out any messages it receives. NB – it assumes the received payloads are strings not binary
- If the first character of the topic “inTopic” is an 1, switch ON the ESP Led, else switch it off
 
- It will reconnect to the server if the connection is lost using a blocking reconnect function. See the ‘mqtt_reconnect_nonblocking’ example for how to achieve the same result without blocking the main loop.
Source Code:
/*------------------------------------------------------------------------------------------------------------------------------
*Author            : Emertxe (http://www.emertxe.com) 
*Date              : Fri 13 Agust  2021 16:00:04 IST
*File              : mqtt_esp32.ino
*Title             : This sketch demonstrates the capabilities of the pubsub library in combination
*                    with the ESP32 board/library.
*Description       : Basic ESP8266 MQTT example                     
*                    It connects to an MQTT server then:
*                    publishes "hello world" to the topic "outTopic" every two seconds
*                    subscribes to the topic "inTopic", printing out any messages
*                    it receives. NB - it assumes the received payloads are strings not binary
*                    If the first character of the topic "inTopic" is an 1, switch ON the ESP Led, else switch it off
*                    It will reconnect to the server if the connection is lost using a blocking
*                    reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to achieve the same result 
*                    without blocking the main loop.
*Installation      : Libraries to be installed:
*                    Open the "Tools -> Library Manger -> search for pubsubclient
*                    select pusubclient by Nick 'O leary and install the latest version
*                    install mosquito broqer on the system
*Execution Steps   : Client : laptop, Serveer : ESP32, Broqer : Mosquito
*                    To subscribe to the topic from server, on client terminal typr
*                    "mosquitto_sub  -t out Topic -u "username" -P "password""
*----------------------------------------------------------------------------------------------------------------------------*/
#include <WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
const char* ssid = "***";
const char* password = "***";
const char* mqtt_server = "192.168.43.118";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  randomSeed(micros());
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is active low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }
}
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(), "jaya", "123qwe")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 50, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
  }
}Example output:
Brief:
- It connects to an MQTT server then:
- publishes temperature value read from DHT11 temperature sensor to the topic “outTopic” every two seconds subscribes to the topic “inTopic”, printing out any messages it receives.
 
- It will reconnect to the server if the connection is lost using a blocking reconnect function. See the ‘mqtt_reconnect_nonblocking’ example for how to achieve the same result without blocking the main loop.
Source Code:
/*-----------------------------------------------------------------------------------------------------------------------------
*Author           : Emertxe (http://www.emertxe.com) 
*Date             : Fri 13 Agust  2021 16:00:04 IST
*File             : mqtt_esp32_temp.ino
*Title            : This sketch reads temperature value from DHT sensor and publish temperature value using mqtt protocol.
*Description      : Basic ESP8266 MQTT example
*                   It connects to an MQTT server then:
*                   publishes temperature value read from DHT11 temperature sensor to the topic "outTopic" every two seconds
*                   subscribes to the topic "inTopic", printing out any messages it receives. 
*                   It will reconnect to the server if the connection is lost using a blocking
*                   reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
*                   achieve the same result without blocking the main loop.
*Installation     : Libraries to be installed:
*                   Open the "Tools -> Manage libraries -> search for pubsubclient
*                   select pusubclient by Nick 'O leary and install the latest version
*                   Open the "Tools -> Manage libraries -> search for Adafruit_unified_sensor
*                   selectr adafruit_unified_sensor from adafruit and install.
*                   Open the "Tools -> Manage libraries -> search for DHT_sensor_library.
*                   Select DHT_sensor_library by adafruit and install it.
*                   install mosquito broqer on the system
*Execution steps :  To subscribe to temperature value on client terminal type
*                   "mosquitto_sub  -t out Topic -u "username" -P "password""
*                   Client : laptop, Serveer : ESP32, Broqer : Mosquito
-------------------------------------------------------------------------------------------------------------------------------*/
#include <WiFi.h>
#include <PubSubClient.h>
#include "DHT.h"
// Update these with values suitable for your network.
#define DHTPIN 4
#define DHTTYPE DHT11
const char* ssid = "***";
const char* password = "*****";
const char* mqtt_server = "192.168.43.118";
WiFiClient espClient;
 
DHT dht(DHTPIN, DHTTYPE);
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup_wifi() 
{
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.print(".");
  }
  randomSeed(micros());
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) 
{
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') 
  {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is active low on the ESP-01)
  } 
  else 
  {
    // Turn the LED off by making the voltage HIGH
    digitalWrite(BUILTIN_LED, HIGH);  
  }
}
void reconnect() 
{
  // Loop until we're reconnected
  while (!client.connected())
  {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str(), "jaya", "123qwe"))
    {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } 
    else 
    {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void setup() 
{ // Initialize the BUILTIN_LED pin as an output
  pinMode(BUILTIN_LED, OUTPUT);     
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
   dht.begin();
}
void loop() 
{
  if (!client.connected()) 
  {
    reconnect();
  }
  client.loop();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  long now = millis();
  if (now - lastMsg > 2000) 
  {
    lastMsg = now;
    ++value;
    snprintf (msg, 50, "temp #%f", t);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
  }
}Raspberry pi sample program output:
Brief:
Source Code:
/*------------------------------------------------------------------------------------------------------------------------------
*Author            : Emertxe (http://www.emertxe.com) 
*Date              : Fri 13 Agust  2021 16:00:04 IST
*File              : blnk.ino
*Title             : Program on demonstrating use of rest api to control ESP32.
*Description       : Example for rest api
*                    In this example ESp32 connects to Blynk server, using authentication token , status of led is controled 
*                    through Blynk app.
*installation      : Libraries to be installed:
*                    Tools -> Manage libraries -> search for Blynk library -> install blynk library
*Execution steps   : Install Blynk app on mobile
*                    Create new project, add new widget, select buttonselect virtual pin and switch and make settings for pull
*                    up or pull down.
-------------------------------------------------------------------------------------------------------------------------------*/ 
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "*****";
// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "****";
char pass[] = "****";
WidgetLED led1(V1);
BlynkTimer timer;
// V1 LED Widget is blinking
void blinkLedWidget()
{
  if (led1.getValue()) {
    led1.off();
    
    Serial.println("LED on V1: off");
  } else {
    led1.on();
    Serial.println("LED on V1: on");
  }
}
void setup()
{
  // Debug console
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
  timer.setInterval(1000L, blinkLedWidget);
}
void loop()
{
  Blynk.run();
  timer.run();
}Example output:
Brief:
Client Side Code:
"""-------------------------------------------------------------------------------------------------------------------
 * Author          : Emertxe (http://www.emertxe.com) 
 * Date            : Fri 13 Agust  2021 16:00:04 IST
 * File            : client.py
 * Title           : Program on demonstrating COAP based server client communication 
 * Description     : Basic Rpi COAP example 
 * Installation    : sudo apt update
 *       	           sudo apt install libcoap-1-0
 *                   pip install Twisted
 *                   pip instal txThings
 * Execution Steps : Change the IP address in client code.
 *	                 Set the IP address to Server IP address, i.e rpi3 IP address		     
 *------------------------------------------------------------------------------------------------------------------"""
import sys
from twisted.internet.defer import Deferred
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from twisted.python import log
import txthings.coap as coap
import txthings.resource as resource
from ipaddress import ip_address
class Agent():
	def __init__(self, protocol):
		self.protocol = protocol
		reactor.callLater(1, self.requestResource)
	def requestResource(self):
		request = coap.Message(code=coap.GET)
		request.opt.uri_path = ('block', )
		request.opt.observe = 0
		request.remote = (ip_address('192.168.1.100'), coap.COAP_PORT)
		d = protocol.request(request, observeCallback = self.printLaterResponse)
		d.addCallback(self.printResponse)
		d.addErrback(self.noResponse)
	def printResponse(self, response):
		print "First result: " + response.payload
	def printLaterResponse(self, response):	
		print "Observer result: " + response.payload
	def noResponse(self, failure):
		print "Failed to fetch resource"
		print failure
log.startLogging(sys.stdout)
endpoint = resource.Endpoint(None)
protocol = coap.Coap(endpoint)
client = Agent(protocol)
reactor.listenUDP(61616, protocol)
reactor.run()Server Side Code:
"""-------------------------------------------------------------------------------------------------------------------
 * Author          : Emertxe (http://www.emertxe.com) 
 * Date            : Fri 13 Agust  2021 16:00:04 IST
 * File            : client.py
 * Title           : Program on demonstrating COAP based server client communication 
 * Description     : Basic Rpi COAP example 
 * Installation    : sudo apt update
 *       	           sudo apt install libcoap-1-0
 *                   pip install Twisted
 *                   pip instal txThings
 * Execution Steps : Change the IP address in client code.
 *	                 Set the IP address to Server IP address, i.e rpi3 IP address		     
 *------------------------------------------------------------------------------------------------------------------"""
import sys
from twisted.internet import defer
from twisted.internet.protocol import DatagramProtocol
from twisted.python import log
import txthings.resource as resource
import txthings.coap as coap
from twisted.internet import reactor, protocol
class BlockResource (resource.CoAPResource):
	def __init__(self):
		resource.CoAPResource.__init__(self)
		self.visible = True
	def render_GET(self, request):
		print 'GET request: ' + request.payload
		payload = "Satya"
		response = coap.Message(code=coap.CONTENT, payload=payload)
		return defer.succeed(response)
	def render_PUT(self, request):
		print 'PUT payload: ' + request.payload
		payload = "CoAP Server...>>>Satya"
		response = coap.Message(code=coap.CHANGED, payload = payload)
		return defer.succeed(response)
#Resource tree creation
log.startLogging(sys.stdout)
root = resource.CoAPResource()
block = BlockResource()
root.putChild('block', block)
endpoint = resource.Endpoint(root)
reactor.listenUDP(coap.COAP_PORT, coap.Coap(endpoint))
reactor.run()Raspberry pi sample program output:
Brief:
Client Side Code:
"""-------------------------------------------------------------------------------------------------------------------
 * Author          : Emertxe (http://www.emertxe.com) 
 * Date            : Fri 13 Agust  2021 16:00:04 IST
 * File            : http_client.py
 * Title           : Program on demonstrating HTTP based server client communication 
 * Description     : Basic Rpi HTTP example, Client sends request for connection, get resonse and prints response.
 * Installation    : sudo apt update
 * Execution Steps : sudo python2 http_client.py
 *                   Change the path of the sample.html file in the server program		     
 *------------------------------------------------------------------------------------------------------------------"""
import httplib  
import sys  
  
#get http server ip  
http_server = sys.argv[1]  
#create a connection  
conn = httplib.HTTPConnection(http_server)  
  
while 1:  
  cmd = raw_input('input command (ex. GET index.html): ')  
  cmd = cmd.split()  
  
  if cmd[0] == 'exit': #tipe exit to end it  
    break  
  #request command to server  
  conn.request(cmd[0], cmd[1])  
  
  #get response from server  
  rsp = conn.getresponse()  
  #print server response and data  
  print(rsp.status, rsp.reason)  
  data_received = rsp.read()  
  print(data_received)  
conn.close()  Server Side Code:
"""-------------------------------------------------------------------------------------------------------------------
 * Author          : Emertxe (http://www.emertxe.com) 
 * Date            : Fri 13 Agust  2021 16:00:04 IST
 * File            : http_server.py
 * Title           : Program on demonstrating HTTP based server client communication 
 * Description     : Basic Rpi HTTP example, server handles the request with HTML response
 * Installation    : sudo apt update
 * Execution Steps : sudo python2 http_server.py
 *                   Change the path of the sample.html file in the server program		     
 *------------------------------------------------------------------------------------------------------------------"""
#!/usr/bin/env python
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import os
#Create custom HTTPRequestHandler class
class CustomHTTPRequestHandler(BaseHTTPRequestHandler):
    #handle GET command
    def do_GET(self):
        rootdir = '/tmp/' #file location
        try:
            if self.path.endswith('.html'):
                f = open(rootdir + self.path) #open requested file
                #send code 200 response
                self.send_response(200)
                #send header first
                self.send_header('Content-type','text-html')
                self.end_headers()
                #send file content to client
                self.wfile.write(f.read())
                f.close()
                return
        except IOError:
            self.send_error(404, 'file not found')
def run():
    print('http server is starting...')
    #ip and port of servr
    #by default http server port is 80
    port = 8080
    server_address = ('127.0.0.1', port)
    httpd = HTTPServer(server_address, CustomHTTPRequestHandler)
    print('http server is running on port ' + str(port))
    httpd.serve_forever()
if __name__ == '__main__':
    run()Html Code:
<head>  
 <title>Sample HTML</title>  
</head>  
<body>  
 <h1>Coding is Awesome</h1>  
 <h1>Hello World</h1>  
</body>Example output:
Brief:
This Program demonstrates the capabilities of pub-sub library in combination with the Rpi board/library.
Pub Code:
"""------------------------------------------------------------------------------------------------------------------
*Author            : Emertxe (http://www.emertxe.com) 
*Date              : Fri 13 Agust  2021 16:00:04 IST
*File              : pub.py
*Title             : This sketch demonstrates the capabilities of the pubsub library in combination
*                    with the Rpi board/library.
*Description       : Basic ESP8266 MQTT example , for publish.
*        	           Establishing Connection To A MQTT Broker
*		                 Use a public MQTT broker provided by Eclipse.
*		                 client.publish is to publish topic.
*Installation      : sudo apt update
*                    sudo apt install mosquito
*                    sudo apt install mosquitto-clients
*                    pip paho-mqtt
*Execution Steps   : sudo python2 sub.py
*-----------------------------------------------------------------------------------------------------------------"""
import paho.mqtt.client as mqtt
broker_url = "iot.eclipse.org"
broker_port = 1883
client = mqtt.Client()
client.connect(broker_url, broker_port)
client.publish(topic="TestingTopic", payload="TestingPayload", qos=1, retain=False)
Sub Code:
"""/*------------------------------------------------------------------------------------------------------------------
*Author            : Emertxe (http://www.emertxe.com) 
*Date              : Fri 13 Agust  2021 16:00:04 IST
*File              : sub.py
*Title             : This sketch demonstrates the capabilities of the pubsub library in combination
*                    with the Rpi board/library.
*Description       : Basic ESP8266 MQTT example , for subscription.
*        	           Establishing Connection To A MQTT Broker
*		                 Use a public MQTT broker provided by Eclipse.
*		                 The on_connect() callback is called each time the client connects/reconnects to the broker
*                    The on_disconnect() callback is called each time the client disconnects/reconnects to the broker
*                    The on_message() callback is used to process messages that are published to asubscribed topic.
*                    
*Installation      : sudo apt update
*                    sudo apt install mosquito
*                    sudo apt install mosquitto-clients
*                    pip paho-mqtt
*Execution Steps   : sudo python2 sub.py
*----------------------------------------------------------------------------------------------------------------"""
import paho.mqtt.client as mqtt
broker_url = "iot.eclipse.org"
broker_port = 1883
def on_connect(client, userdata, flags, rc):
   print("Connected With Result Code " (rc))
def on_message(client, userdata, message):
   print("Message Recieved:" + message.payload.decode())
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(broker_url, broker_port)
client.subscribe("TestingTopic", qos=1)
client.publish(topic="TestingTopic", payload="TestingPayload", qos=1, retain=False)
client.loop_forever()
Raspberry pi sample program output:
Brief:
This Program demonstrates the capabilities of pub-sub library in combination with the Rpi board/library.
Pub Code:
"""-------------------------------------------------------------------------------------------------------------------
*Author            : Emertxe (http://www.emertxe.com) 
*Date              : Fri 13 Agust  2021 16:00:04 IST
*File              : pub.py
*Title             : This sketch demonstrates the capabilities of the pubsub library in combination with the Rpi 
*                    board/library.
*Description       : Basic Rpi MQTT example 
*        	           Establishing Connection To A MQTT Broker, publishes message "TestingPayload" to the topic 
*                    "TestingTopic".
*		                             
*Installation      : sudo apt update
*                    sudo apt install mosquito
*                    sudo apt install mosquitto-clients
*                    pip paho-mqtt
*Execution Steps   : sudo python2 pub.py
*                 
*-------------------------------------------------------------------------------------------------------------------"""
#!/usr/bin/env python3
import paho.mqtt.client as mqtt
broker_url = "127.0.0.1"
broker_port = 1883
#rc connection result rc = 0 if successfull else 1 if refused
def on_connect(client, userdata, flags, rc):
   print("Connected With Result Code ", rc)
   #print("Connected With Result Code " (rc))
client = mqtt.Client()
client.on_connect = on_connect
client.connect(broker_url, broker_port)
client.publish(topic="TestingTopic", payload="TestingPayload", qos=1, retain=False)
client.loop_forever()
Sub Code:
"""-----------------------------------------------------------------------------------------------------------------
*Author            : Emertxe (http://www.emertxe.com) 
*Date              : Fri 13 Agust  2021 16:00:04 IST
*File              : sub.py
*Title             : This sketch demonstrates the capabilities of the pubsub library in combination
*                    with the Rpi board/library.
*Description       : Basic Rpi MQTT example 
*        	           Establishing Connection To A MQTT Broker, subscribes to the topic "TestingTopic".                  
*Installation      : sudo apt update
*                    sudo apt install mosquito
*                    sudo apt install mosquitto-clients
*                    pip paho-mqtt
*Execution Steps   : sudo python2 sub.py              
*------------------------------------------------------------------------------------------------------------------"""
import paho.mqtt.client as mqtt
broker_url = "127.0.0.1"
broker_port = 1883
# 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 ", (rc))
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, message):
    print("Message: " + message.payload.decode())
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(broker_url, broker_port)
client.subscribe("TestingTopic", qos=1)
client.loop_forever()
Raspberry pi sample program output:

 
                                                     
                                                     
                                                     
                                                     
                                                     
                                                     
                                                    