I want to use the rPi as a thermostat so I wrote this code. What it basically does it reads the temp and sends it back to the client, some client will then issue a command ON or OFF and based on this it will start/stop a relay.
What I can't figure out is: when a client connects, the server send back the temp and if the client sends ack a 'do nothing' command then the signal to the relay is set to OFF. But this is not possible from the code and the logs don't show a 'set heater OFF' still the relay is shut down. I suspect some interference with GPIO, maybe when it just reads the temp and then does nothing with the heater something happens (as if the signal on heaterPin is reset just because i use the dataPink and clkPin)
import time import socket import threading import RPi.GPIO as GPIO import logging from threading import Timer time.sleep(2) dataPin = 11 clkPin = 7 heaterPin = 13 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) logging.basicConfig(format='%(lineno)d %(asctime)s %(message)s', filename='/home/pi/thermostat/server.log',level=logging.DEBUG) logger = logging.getLogger('thermoLog') from sht1x.Sht1x import Sht1x as SHT1x termo = SHT1x(dataPin, clkPin, SHT1x.GPIO_BOARD) status = '' statusEvent = threading.Event() def heaterOn(): GPIO.setup(heaterPin, GPIO.OUT) GPIO.output(heaterPin, True) logger.info("set heater: ON") statusEvent.set() def heaterOff(): GPIO.setup(heaterPin, GPIO.OUT) GPIO.output(heaterPin, False) logger.info("set heater: OFF") statusEvent.clear() def startServer(): #GPIO.setmode(GPIO.BOARD) try: GPIO.setup(heaterPin, GPIO.OUT) GPIO.output(heaterPin, False) logger.info("set heater default: OFF") status = 'OFF' server.bind(('localhost', 7777)) server.listen(1); except Exception as e: logger.error("Exception on server init " + str(e)) while (True): try: (client, addr) = server.accept() temperature = str(termo.read_temperature_C()) client.sendall(temperature) command = repr(client.recv(1024)).replace('\'', '') logger.info("got command: " + command) if (str(command) == 'ON'): heaterOn() status = 'ON' elif (str(command) == 'OFF'): heaterOff() status = 'OFF' reply(client, temperature, status) client.close() except Exception as e: logger.error("Exception on client communication " + str(e)) def reply(client, temp, status): client.sendall(temp + '-' + status) def main(): s = threading.Timer(1, startServer) s.start() logger.info("SERVER START") return if __name__ == "__main__": main()