ESP8266 as TCP Client for IoT development using Raspberry Pi3

This post is intended to help beginners to get started with ESP8266 and Raspberry Pi for IoT development. ESP8266 is used as a TCP client which connects to a TCP server on the network/LAN for sending and receiving data.

RaspberryPi_Logoesp

Why TCP Server-client communication?

  • Bi-directional
  • Speed – almost real-time
  • Allows multiple clients to interact with the server simultaneously
  • Can be converted to a publish-subscribe model with little modification in the server side programming.

 

Connecting ESP8266 with RaspberryPi

RaspberryPi can be used directly to interface with the ESP8266 module with the following connections

ESP8266                RASPBERRY-PI

VCC                          3.3V

GND                         GND

TX                             RX

RX                             TX

CH_PD                    3.3V

 

Sample code:


__author__ = 'dhanish'

import serial
import sys
import os
import time
import thread

import yaml

using_Rpi = 1
global wifiConnected
global tcpConnected


# if using_Rpi == 1:
# import RPi.GPIO as GPIO

def init_rfid(comport="COM4", baudrate=9600):
    esp_serial = serial.Serial()
    esp_serial.port = comport
    esp_serial.baudrate = baudrate
    esp_serial.timeout = 20
    esp_serial.xonxoff = False
    esp_serial.rtscts = False
    esp_serial.bytesize = serial.EIGHTBITS
    esp_serial.parity = serial.PARITY_NONE
    esp_serial.stopbits = serial.STOPBITS_ONE

    return esp_serial


def openPort(esp_serial):
    try:
        esp_serial.open()
        esp_serial.flushInput()
        esp_serial.flushOutput()
    except:
        print 'Cannot open rfid serial port'
        sys.exit()

    return esp_serial


def closePort(esp_serial):
    esp_serial.close()


def read_esp_and_display(esp_serial):
    while True:
        response = esp_serial.readline().rstrip()
        print response
        global wifiConnected
        global tcpConnected
        if ((response == "WIFI DISCONNECT") or (response ==  "no ip")):
            wifiConnected = 0
        elif (response == "WIFI CONNECTED"):
            wifiConnected = 1
        elif ((response == "link is not valid") or (response == "CLOSED")):
            tcpConnected = 0
        elif ((response == "CONNECT") or (response == "ALREADY CONNECTED")):
            tcpConnected = 1

    time.sleep(.1)
    esp_serial.close()


config = yaml.load(open('config.yaml', 'r'))

esp_serial = init_rfid(config["serial"]["comport"], config["serial"]["baudrate"])
esp_serial = openPort(esp_serial)

thread.start_new_thread(read_esp_and_display, (esp_serial,))  # start seperate thread for rfid and return
# esp_serial.write('+++')
# time.sleep(2)

wifiConnected = 1
tcpConnected = 1

esp_serial.write('AT+CWMODE=1\r\n')
time.sleep(2)
#
esp_serial.write('AT+CWQAP\r\n')
time.sleep(2)
#
esp_serial.write('AT+CIPSTA_DEF="'+config["wifi"]["staticip"]+'"\r\n')
time.sleep(2)
#
#
esp_serial.write('AT+CWJAP="'+config["wifi"]["ssid"]+'","'+config["wifi"]["password"]+'"\r\n')
time.sleep(20)

# wifiConnected = 1

esp_serial.write("AT+CIFSR\r\n")
time.sleep(2)

esp_serial.write("AT+CIPMODE=0\r\n")
time.sleep(2)
# esp_serial.write("AT+CIPCLOSE\r\n")
# time.sleep(3)

esp_serial.write('AT+CIPSTART="TCP","'+ config["client"]["serverip"] +'",'+ config["client"]["serverport"] + ',100\r\n')
time.sleep(5)

i = 0
while True:

    while (wifiConnected and tcpConnected):
        i = i + 1
        msg = str(i) + '\r\n'

        # esp_serial.write("AT+CIPSEND=9\r\n")

        esp_serial.write("AT+CIPSEND=" + str(len(msg)) + "\r\n")
        time.sleep(0.2)
        # msg = "dhanish\r\n"
        esp_serial.write(msg)
        time.sleep(0.5)

    while (wifiConnected == False):
        esp_serial.write('AT+CWJAP="'+config["wifi"]["ssid"]+'","'+config["wifi"]["password"]+'"\r\n')
        time.sleep(20)

    while (wifiConnected and (tcpConnected == False)):
        esp_serial.write('AT+CIPSTART="TCP","'+ config["client"]["serverip"] +'",'+ config["client"]["serverport"] + ',100\r\n')
        time.sleep(5)


# esp_serial.write("AT+CIPCLOSE\r\n")
# time.sleep(3)

Create a file named config.yaml in the code folder and put the following contents into it

 

wifi:
    ssid: "username"
    password: "password"
    staticip: "192.168.1.102"

client:
    serverip: "192.168.1.3"
    serverport: "8081"

serial:
    comport: "COM4"
    baudrate: 9600

Advertisements

One thought on “ESP8266 as TCP Client for IoT development using Raspberry Pi3

  1. Trying To Build A Very Small Temp Sender,, Wireless To Tx 50 Metres To A Data
    Collector Of Some Sort Was Ad Ised To Use Esp8266 But Have No Idea How To
    Go About Building One Yet, Dose anyone Have some advice Please, Im Wanting
    To Be Able To Read Temps On My I Pad If possible And Data Log Them.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s