You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

树莓派间基于Python TCP/IP Socket传输传感器数据的问题求助

Hey there! Let's work through your Raspberry Pi TCP socket setup issues—since you mentioned you’ve got code written but hit snags, here are the most common fixes and best practices to get your sensor data flowing to the server and database smoothly:

1. First, Fix Basic Connection Problems
  • Double-check both Pis are on the same local network. On the server Pi, make sure its firewall isn’t blocking your listening port (e.g., if using port 5000, run sudo ufw allow 5000/tcp). You can also temporarily disable the firewall for testing: sudo ufw disable
  • Critical: In your server code, bind to 0.0.0.0 instead of 127.0.0.1—binding to localhost means only the server Pi itself can connect, not other devices. Example:
    server_socket.bind(('0.0.0.0', 5000))
    
  • On the client, use the server Pi’s local IP address (like 192.168.1.100) instead of a hostname to avoid DNS resolution bugs.
2. Make Sensor Data Transmission Reliable
  • Stop sending raw strings—format data as JSON for consistent parsing on the server. This makes it easy to add more sensor fields later too. Client code example:
    import json
    # Assume sensor_data is your reading: {'pi_id': 'client_1', 'temp': 25.4, 'humidity': 62.1}
    formatted_data = json.dumps(sensor_data).encode('utf-8')
    client_socket.sendall(formatted_data)
    
  • Fix "packet sticking" issues on the server. A simple method is to send the data length first, then the actual data:
    import json
    while True:
        # First receive 4 bytes for data length
        length_bytes = client_conn.recv(4)
        if not length_bytes:
            break
        data_len = int.from_bytes(length_bytes, byteorder='big')
        # Then receive the full data payload
        raw_data = client_conn.recv(data_len).decode('utf-8')
        sensor_data = json.loads(raw_data)
        # Now process and store the data
    
3. SQLite Database Best Practices
  • Don’t open/close the database connection every time you store data—keep a persistent connection open (just remember SQLite uses file-level locks, so for multi-client setups, wrap writes in a lock):
    import sqlite3
    from threading import Lock
    
    # Initialize DB once at startup
    db_lock = Lock()
    conn = sqlite3.connect('sensor_readings.db', check_same_thread=False)
    cursor = conn.cursor()
    cursor.execute('''CREATE TABLE IF NOT EXISTS readings
                     (timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
                      pi_id TEXT, temp REAL, humidity REAL)''')
    conn.commit()
    
    # When storing data:
    with db_lock:
        cursor.execute("INSERT INTO readings (pi_id, temp, humidity) VALUES (?, ?, ?)",
                      (sensor_data['pi_id'], sensor_data['temp'], sensor_data['humidity']))
        conn.commit()
    
  • Always use parameterized queries like the example above—this avoids SQL injection risks (even for local setups, it’s a good habit!).
4. Prep for Future Multi-Client & Web Server Expansion
  • Your current single-threaded server can only handle one client at a time. Switch to multi-threading to support multiple Pis:
    import threading
    
    def handle_client(client_conn):
        # Full data receive/parse/store logic here
        client_conn.close()
    
    # In your server main loop:
    while True:
        client_socket, client_addr = server_socket.accept()
        print(f"Connected to {client_addr}")
        client_thread = threading.Thread(target=handle_client, args=(client_socket,))
        client_thread.start()
    
  • For your future web server goal: Consider ditching raw sockets entirely and using a simple HTTP API with Flask or FastAPI. It’s easier to maintain and scale. Example Flask endpoint:
    from flask import Flask, request, jsonify
    import sqlite3
    
    app = Flask(__name__)
    
    @app.route('/submit-sensor-data', methods=['POST'])
    def receive_data():
        sensor_data = request.get_json()
        conn = sqlite3.connect('sensor_readings.db')
        cursor = conn.cursor()
        cursor.execute("INSERT INTO readings (pi_id, temp, humidity) VALUES (?, ?, ?)",
                      (sensor_data['pi_id'], sensor_data['temp'], sensor_data['humidity']))
        conn.commit()
        conn.close()
        return jsonify({"status": "success"}), 200
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000)
    
    And the client can send data with the requests library (way simpler than sockets):
    import requests
    sensor_data = {'pi_id': 'client_1', 'temp': 25.4, 'humidity': 62.1}
    requests.post('http://your-web-server-ip:5000/submit-sensor-data', json=sensor_data)
    

If you’ve got specific error messages, code snippets that are failing, or weird behavior (like data missing from the DB), share those details and I can help you narrow it down further!

内容的提问来源于stack exchange,提问作者Thijs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:30:21