#!/usr/bin/env python # Import Libraries import socket import os import glob import Adafruit_BBIO.GPIO as GPIO import datetime from datetime import * import time from time import time server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(("192.168.0.20",5000)) server.listen(5) # Finds the correct device file that holds the temperature data base_dir = '/sys/devices/w1_bus_master1/' device_folder = glob.glob(base_dir + '22*')[0] device_file = device_folder + '/w1_slave' # A function that reads the sensors data def read_temp_raw(): try: f = open(device_file, 'r') # Opens the temperature device file lines = f.readlines() # Returns the text f.close() except: lines="" return lines # Convert the value of the sensor into a temperature def read_temp(): lines = read_temp_raw() # Read the temperature 'device file' # While the first line does not contain 'YES', wait for 0.2s # and then read the device file again. while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw() # Look for the position of the '=' in the second line of the # device file. equals_pos = lines[1].find('t=') # If the '=' is found, convert the rest of the line after the # '=' into degrees Celsius, then degrees Fahrenheit if equals_pos != -1: temp_string = lines[1][equals_pos+2:] temp_c = float(temp_string) / 1000.0 # temp_f = temp_c * 9.0 / 5.0 + 32.0 # return temp_c, temp_f return temp_c print "TCP server listening on port 5000" while 1: myclient, address = server.accept() print "Connected to ", address #confirm connection myclient.send("0"+'\r') while 1: # wait for client data data = myclient.recv(512) today = datetime.now() # print "Received -->"+data+"<-- at "+today.strftime('%H:%M:%S') rxTime = today.microsecond/1000+today.second*1000 if (data == "q") or (data == "qq"): print "Closing Connection" myclient.close() break elif (data == 't'): t=read_temp() newdata=str(t) today = datetime.now() txTime = today.microsecond/1000+today.second*1000 print "Received -->"+data+"<-- : "+newdata+"C" myclient.send('T='+newdata+'\r') print "Acquisition time = "+str(txTime-rxTime)+"mS" else: newdata=str(float(data)*2) print "Converted:" , newdata myclient.send(newdata+'\r') if (data == "qq"): server.close() print "TCP server is down" break else: print "TCP server still listening on port 5000"