Tuesday, April 30, 2019

Server and Client Send Actual Sensor Data over Network using Raspberry Pi¶

Lab 3

Server and Client Send Actual Sensor Data over Network using Raspberry Pi

objective

In this Experiment we shall learn to create our own server and client with raspberyy pi uisng python Socket Programming.

Our Tagrget is to create a server. the server would be Running 24x7 on Raspberry pi and server is always listening for request from client When a client request server it shall send the Temperature and Humidty over Network using Socket Programming

In [17]:
from IPython.display import YouTubeVideo
YouTubeVideo('QihjI84Z2tQ')
Out[17]:

Getting Started with Raspberry pi

In [21]:
from IPython.display import YouTubeVideo
YouTubeVideo('qL2ClHYEuog')
Out[21]:

Connection Diagram

In [14]:
%%html
<img src="http://www.circuitbasics.com/wp-content/uploads/2015/12/How-to-Setup-the-DHT11-on-the-Raspberry-Pi-Three-pin-DHT11-Wiring-Diagram.png" , width=600, height=300>

DHT Pinout

In [15]:
%%html
<img src="http://www.circuitbasics.com/wp-content/uploads/2015/12/DHT11-Pinout-for-three-pin-and-four-pin-types-2.jpg" , width=600, height=300>

Step 1: Create Server

Define the Library

In [2]:
import socket
import numpy as np
import encodings

Define the HOST and PORT

In [ ]:
HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)

For the Experiment we shall send Dummy Data and then once we know the concept we can send actual Sensor value over the socket programming.

Define the function which will send dummy data when client sends request

In [ ]:
def random_data():

    x1 = np.random.randint(0, 55, None)         # Dummy temperature
    y1 = np.random.randint(0, 45, None)         # Dummy humidigy
    my_sensor = "{},{}".format(x1,y1)
    return my_sensor                            # return data seperated by comma

Define the actual server when client sends string Data it shall send Data

In [ ]:
def my_server():

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        print("Server Started waiting for client to connect ")
        s.bind((HOST, PORT))
        s.listen(5)
        conn, addr = s.accept()

        with conn:
            print('Connected by', addr)
            while True:

                data = conn.recv(1024).decode('utf-8')

                if str(data) == "Data":

                    print("Ok Sending data ")

                    my_data = random_data()

                    x_encoded_data = my_data.encode('utf-8')

                    conn.sendall(x_encoded_data)

                elif  str(data) == "Quit":
                    print("shutting down server ")
                    break


                if not data:
                    break
                else:
                    pass
In [ ]:
if __name__ == '__main__':
    while 1:
        my_server()

Explanation

when client sends Data as a string server will send sensor data over the network

Entire Code for Server

In [ ]:
import socket
import numpy as np
import encodings

HOST = '127.0.0.1'  # Standard loopback interface address (localhost)
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)


def random_data():

    x1 = np.random.randint(0, 55, None)         # Dummy temperature
    y1 = np.random.randint(0, 45, None)         # Dummy humidigy
    my_sensor = "{},{}".format(x1,y1)
    return my_sensor                            # return data seperated by comma




def my_server():

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        print("Server Started waiting for client to connect ")
        s.bind((HOST, PORT))
        s.listen(5)
        conn, addr = s.accept()

        with conn:
            print('Connected by', addr)
            while True:

                data = conn.recv(1024).decode('utf-8')

                if str(data) == "Data":

                    print("Ok Sending data ")

                    my_data = random_data()

                    x_encoded_data = my_data.encode('utf-8')

                    conn.sendall(x_encoded_data)

                elif  str(data) == "Quit":
                    print("shutting down server ")
                    break


                if not data:
                    break
                else:
                    pass


if __name__ == '__main__':
    while 1:
        my_server()

Step 2: Write the Code for Client

Import library

In [ ]:
import socket
import threading
import time

Define the HOST and PORT

In [ ]:
HOST = '192.168.0.111'  # The server's hostname or IP address
PORT = 65432        # The port used by the server

we need to process the Data that server sends us lets us define a function for that

In [ ]:
def process_data_from_server(x):
    x1, y1 = x.split(",")
    return x1,y1

Write the Client Code

In [ ]:
def my_client():
    threading.Timer(11, my_client).start()

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST, PORT))

        my = input("Enter command ")

        #my = "Data"

        my_inp = my.encode('utf-8')

        s.sendall(my_inp)

        data = s.recv(1024).decode('utf-8')

        x_temperature,y_humidity = process_data_from_server(data)

        print("Temperature {}".format(x_temperature))
        print("Humidity {}".format(y_humidity))

        s.close()
        time.sleep(5)
In [ ]:
if __name__ == "__main__":
    while 1:
        my_client()

Entire Client Code

In [ ]:
import socket
import threading
import time


HOST = '192.168.0.111'  # The server's hostname or IP address
PORT = 65432        # The port used by the server


def process_data_from_server(x):
    x1, y1 = x.split(",")
    return x1,y1


def my_client():
    threading.Timer(11, my_client).start()

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST, PORT))

        my = input("Enter command ")

        #my = "Data"

        my_inp = my.encode('utf-8')

        s.sendall(my_inp)

        data = s.recv(1024).decode('utf-8')

        x_temperature,y_humidity = process_data_from_server(data)

        print("Temperature {}".format(x_temperature))
        print("Humidity {}".format(y_humidity))

        s.close()
        time.sleep(5)


if __name__ == "__main__":
    while 1:
        my_client()

Great Job try the Code and lets send Actual Sensor Data over Network

Server Code which will run on Raspberry pi

In [ ]:
import socket
import numpy as np
import encodings
import Adafruit_DHT


HOST = '192.168.1.4'  # Standard loopback interface address (localhost)
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)


def random_data():
    pin = 4
    sensor = Adafruit_DHT.DHT22
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

    if humidity is not None and temperature is not None:
        print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity))
        print("data was written on database T{} H{}".format(temperature,humidity))
        data = '{},{}'.format(temperature,humidity)
        return data





def my_server():

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        print("Server Started waiting for client to connect ")
        s.bind((HOST, PORT))
        s.listen(5)
        conn, addr = s.accept()

        with conn:
            print('Connected by', addr)
            while True:

                data = conn.recv(1024).decode('utf-8')

                if str(data) == "Data":

                    print("Ok Sending data ")

                    my_data = random_data()

                    x_encoded_data = my_data.encode('utf-8')

                    conn.sendall(x_encoded_data)

                elif  str(data) == "Quit":
                    print("shutting down server ")
                    break


                if not data:
                    break
                else:
                    pass


if __name__ == '__main__':
    while 1:
        my_server()

Client Code will be same as Above.

9 comments:

  1. You have done amazing work, i will be thankful if you explain these lines
    if __name__ == '__main__':
    while 1:
    my_server()

    RegardsL Humza

    ReplyDelete
    Replies
    1. 1 ist true, 0 is false. so "while 1:" means "while true"

      Delete
    2. Pythonist: Server And Client Send Actual Sensor Data Over Network Using Raspberry Pi¶ >>>>> Download Now

      >>>>> Download Full

      Pythonist: Server And Client Send Actual Sensor Data Over Network Using Raspberry Pi¶ >>>>> Download LINK

      >>>>> Download Now

      Pythonist: Server And Client Send Actual Sensor Data Over Network Using Raspberry Pi¶ >>>>> Download Full

      >>>>> Download LINK EA

      Delete
  2. Hi i want to ask question about creating comm and sending messages bwtween 1 server and 5 clients via wifi socket i mean the server is at first running a init_script and sends a couples of messages to the 5 clients and then enters to a inifinty loop and wait for incoming data from the clients and than analyze this data,,each clinet sends its data to the server after he finished his analyze (for example l have ultrasonic sensor which messuring the elapsed time of someone who passes obstcale and in the end sends it to the server and think i have 5 obstacles so he needs to pass 5 obstacles and send the time of each of them to server and the server in the end creating Excel file with the total time (5 obstacles time)..i really would like for help in the socket here its somthing rh drives me crazy and i would be greatfull for help thnx (i have couple of files that i wrote )

    ReplyDelete
  3. File "D:\rasbeery pi\entire server code.py", line 2, in
    import numpy as np
    ModuleNotFoundError: No module named 'numpy'

    this error found whilw running entire server code i dont't know to solve it plz help me out

    ReplyDelete
    Replies
    1. Hi bro!, you must install the pk of numpy previusly. Run 'python install numpy' or 'py install numpy' or similar command from cmd console in Windows (Windows+r and enter 'cmd' for open this console...)
      For 'encodings' pkg is similar: enter 'py install encodings' from cmd console. See this link https://datatofish.com/install-package-python-using-pip/

      Delete
  4. This comment has been removed by the author.

    ReplyDelete
  5. Hello hope you are doing well. At last I have found something related to my work. Kindly help me out with sending adxl345 data from one pi to another pi from controlling the motors.
    Please do reply me, I'll be waiting for your kind reply.
    Thankyou.
    Usman Gillani
    usman.gilani10205@gmail.com

    ReplyDelete
  6. Pythonist: Server And Client Send Actual Sensor Data Over Network Using Raspberry Pi¶ >>>>> Download Now

    >>>>> Download Full

    Pythonist: Server And Client Send Actual Sensor Data Over Network Using Raspberry Pi¶ >>>>> Download LINK

    >>>>> Download Now

    Pythonist: Server And Client Send Actual Sensor Data Over Network Using Raspberry Pi¶ >>>>> Download Full

    >>>>> Download LINK

    ReplyDelete

Developer Guide: Getting Started with Flink (PyFlink) and Hudi - Setting Up Your Local Environment and Performing CRUD Operations via flink

flink-hudi-final Install Flink and Python ¶ conda info --envs # Create ENV conda ...