Home > Software engineering >  sending sensor data over a socket
sending sensor data over a socket

Time:10-15

I wanna send dht11's temperature and humidity data from raspberrypi to pc.

but when I run this code:

import RPi.GPIO as GPIO
import dht11
import time
import datetime
GPIO.setwarnings(True)
GPIO.setmode(GPIO.BCM)
instance = dht11.DHT11(pin=18)

import socket

HOST = '192.168.35.129'

PORT = 9999        
 
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

server_socket.bind((HOST, PORT))

server_socket.listen()

client_socket, addr = server_socket.accept()


print('Connected by', addr)


try:
        while True:
                result = instance.read()
                if result.is_valid():
                        print("Last valid input: "   str(datetime.datetime.now()))
                        print("Temperature: %-3.1f C" % result.temperature)
                        print("Humidity: %-3.1f %%" % result.humidity)
                        client_socket.send(result)
                        time.sleep(6)

except KeyboardInterrupt:
        print("Cleanup")
        GPIO.cleanup()


client_socket.close()
server_socket.close()

I get this error:

Traceback (most recent call last):
 File "/home/pi/Documents/testsev.py", line 36, in <module>
   client_socket.send(result)
 TypeError: a bytes-like object is required, not 'DHT11Result'

I think I have to convert result to form of bytes, but I don't how to do it.

How can I successfully send this data to server and does this code got anything to be changed to be run well?

CodePudding user response:

You need to serialize the data

For example, using JSON

import json

if result.is_valid():
    data = {'temp': result.temperature, 'humidity': result.humidity}
    client_socket.send(json.dumps(data).encode('utf-8'))
  • Related