def readTemperature(): def output_data(dtStamp, temperature, humidity): date = datetime.datetime.fromtimestamp(dtStamp).isoformat() print("Date: {}, Temperature: {:g}*C, Humidity: {:g}%\n".format( date, temperature, humidity)) return [True, date, temperature, humidity] def readWithRetry(reads): while reads > 0: try: dtStamp, gpio, status, temperature, humidity = sensor.read( reads <= 1) #read DHT device if (status == DHT.DHT_GOOD): return output_data( dtStamp, temperature, humidity) # Return after successful read time.sleep(.5) reads -= 1 print( "Status: {} - Failed to get a reading, reads remaining: {}." .format(status, reads)) except KeyboardInterrupt: break # Failed to get a reading return [ False, datetime.datetime.fromtimestamp(dtStamp).isoformat(), 0, 0 ] sensor = DHT.sensor(pi, SETTINGS["DHT_GPIO"], model=SETTINGS["DHT_SENSOR"]) return readWithRetry(SETTINGS["DHT_READS"])
def main(): lcd=LCD.LCD() lcd.blight(1) while(True): try: home_conditions = DHT.requestData() line1 = "{0:0.1f} C and {1:0.1f}%".format(home_conditions['temp'], home_conditions['hum']) weather_dict = weather.get_weather() line2 = "Outside feels %d" % (int(weather_dict['out_feel'])) line3 = "Rpi " + commands.getoutput('vcgencmd measure_temp') lcd.sendText(1, line1) lcd.sendText(2, line2) time.sleep(10) lcd.sendText(1, line1) lcd.sendText(2, line3) time.sleep(10) except Exception,e: print e lcd._cleanUp() quit() except KeyboardInterrupt: print 'User interrupted' lcd._cleanUp() quit()
def get_replica_buckets(dest_host, dest_port_low, dest_port_high, timeout, key): viewleader_sock = common_functions.create_connection( dest_host, dest_port_low, dest_port_high, timeout, True) view, epoch = get_viewleader_info(viewleader_sock) viewleader_sock.close() replica_buckets = DHT.bucket_allocator(key, view) return replica_buckets
def setup(): global dht GPIO.setmode(GPIO.BOARD) GPIO.setup(irrigationPin, GPIO.OUT, initial=GPIO.LOW) #Setup relay GPIO.setup(pirPin, GPIO.IN) #Setup pir dht = DHT.DHT(dhtPin) #Setup dht LCD.lcd_setup() #Setup lcd
def get_home_conditions(): """ Returns a line ready for the LCD with home conditions """ home_conditions = DHT.requestData() return "{0:0.1f} C and {1:0.1f}%".format(home_conditions["temp"], home_conditions["hum"])
def __init__(self): # Temperature Sensor self.PI = pigpio.pi() self.GPIO_PIN = 4 if self.pi_connected(): self.sensor = DHT.sensor(self.PI, self.GPIO_PIN) else: exit()
def __init__(self, server_name, max_data_size, lock_size): self.lock_size = lock_size self.lock_map = dict() self.init_locks() self.lock_con = threading.Lock() self.max_data_size = max_data_size self.connections = [] self.node_info = config.nodes self.server_name = server_name self.dht_table = DHT.DHT(self.server_name) self.put_nums = 0 self.initial() self.ring = consist_hash().h_ring()
def init_default_conf(): """ Sets up a default configuration for DFS: uses $HOME/.dfs as the config dir, reads the default configuration from $HOME/.dfs/dfsrc, and sets up the logging system to use the file dfs.log in the configuration directory """ global default_config_dir, default_config, default_log_file, default_config_file, dht # Creates a directory to the default config, if it does not exists. default_config_dir = os.path.expanduser('~%s.dfs' % os.path.sep) # Create the default config path if it does not exists if not os.path.exists(default_config_dir): os.mkdir(default_config_dir) default_config_file = default_config_dir + os.path.sep + 'dfsrc' default_log_file = default_config_dir + os.path.sep + 'dfs.log' # Load the default config file if not os.path.exists(default_config_file): open(default_config_file, 'w').close() default_config = utils.Config() default_config.load(open(default_config_file, 'r')) # Configures the logging system utils.configure_logging( level=logging.INFO, format='%(asctime)s %(name)s %(levelname)s %(message)s', datefmt='%H:%M:%S', filename=default_log_file, filemode='w') logging.info('Default configuration: %s' % default_config_file) # sets default configuration, if not set changed = False if not default_config.get('DHT:datadir'): default_config.set('DHT:datadir', default_config_dir + os.path.sep + 'dhtdata') changed = True if not default_config.get('Main:UID'): default_config.set('Main:uid', utils.random_string(16)) changes = True if not default_config.get('Main:nick'): default_config.set('Main:nick', utils.random_nick()) changed = True if not default_config.get('Keys:kf'): logging.warning('There are not file key') if not default_config.get('Keys:kd'): logging.warning('There are not description key') if changed: default_config.save(open(default_config_file, 'w')) # Default DHT: a local DHT dht = DHT.LocalDHT(default_config)
def createInstances(self): for o in sensorList: if self.instancesList.getData(None, o['name']) is None: if o['name'][0:3] == 'dht': instance = DHT(o['name'], o['pin'][0]) self.instancesList.addData(instance) elif o['name'][0:3] == 'hcr': instance = HCR(o['name'], o['pin'][0], o['pin'][1]) self.instancesList.addData(instance) elif o['name'][0:3] == 'pir': instance = PIR(o['name'], o['pin'][0]) self.instancesList.addData(instance) else: print('error al generar instancia')
def update_local_data(*argc, **argv): dht = DHT.get_dht() if dht is None: return global hour_id if hour_id not in local_data.keys(): local_data[hour_id] = [dht] else: local_data[hour_id].append(dht) prev_hour_id = hour_id - 1 if prev_hour_id < 0: sum_tmp = 0 sum_hum = 0 cur_hour_len = len(local_data[hour_id]) if cur_hour_len <= 0: return for (tmp, hum) in local_data[hour_id]: sum_tmp += tmp sum_hum += hum cur_local_tmp = sum_tmp / cur_hour_len cur_local_hum = sum_hum / cur_hour_len avg_data[hour_id] = (cur_local_tmp, cur_local_hum) update_msg1(cur_local_tmp, cur_local_hum)
def process_msg(self, recvd_msg, addr, sock): function_from_cmd = recvd_msg[ "cmd"] # takes function arguments from received dict if (function_from_cmd == 'query_servers'): common_functions.send_msg(sock, viewleader_rpc.query_servers(self.epoch), False) elif (function_from_cmd == 'heartbeat'): new_id = recvd_msg["args"][0] port = recvd_msg["args"][1] # src port viewleader_rpc.heartbeat(new_id, port, addr, sock) elif (function_from_cmd == 'lock_get'): lock_name = recvd_msg["lock_name"] requester_id = recvd_msg["requester_id"] if (viewleader_rpc.lock_get(lock_name, requester_id) == True): common_functions.send_msg(sock, "{'status': 'granted'}", False) else: common_functions.send_msg(sock, "{'status': 'retry'}", False) print("Sending retry message to client.") elif (function_from_cmd == 'lock_release'): lock_name = recvd_msg["lock_name"] requester_id = recvd_msg["requester_id"] if (viewleader_rpc.lock_release(lock_name, requester_id) == True): common_functions.send_msg(sock, "{'status': 'ok'}", False) else: common_functions.send_msg(sock, "{'status': 'not ok'}", False) elif (function_from_cmd == 'get_buckets'): key = recvd_msg["key"] replica_buckets = DHT.bucket_allocator(key, viewleader_rpc.view) common_functions.send_msg(sock, replica_buckets, False) elif (function_from_cmd == 'update_view'): curr_epoch = self.update_view() common_functions.send_msg(sock, {'Current Epoch': curr_epoch}, False) elif (function_from_cmd == 'rebalance'): msg = recvd_msg['msg'] print(msg) else: print("Rejecting RPC request because function is unknown.")
def main(): print("\n\nStarting - {}".format(machine.reset_cause())) while True: try: # Establish WiFi connection here interface = WiFi.connect_wifi(Config.wifi_ssid, Config.wifi_pass) if interface: print('Connected: ', interface.ifconfig()) # If we've got somewhere to write the data, read the sensors. # Deliberately do the DHT22 read last to maximise the chance of it having had long enough # to stabilise (only one read every 2 seconds) measurements = '' measurements += DS18B20.read_ds(Config.onewirePin, Config.location) measurements += DHT.read_dht(Config.dhtPin, Config.location) if measurements: print('\nSending to {}\n{}'.format(Config.database, measurements)) print('HTTP:{0}'.format( Influx.send(Config.database, measurements))) else: print('No sensors read successfully.') except KeyboardInterrupt: print("Caught keyboard interrupt") enter_sleep = False except Exception as e: import sys print("Unexpected error ", e) sys.print_exception(e) finally: if Config.deep_sleep: print('Zzzz....') Deepsleep.deep_sleep(Config.sampleTime * 1000) # This will only be executed if Deepsleep is disabled print('Dozing....') time.sleep(Config.sampleTime)
def loop(): dht = DHT.DHT(DHTPin) #create a DHT class object sumCnt = 0 #number of reading times while (True): sumCnt += 1 #counting number of reading times chk = dht.readDHT11( ) #read DHT11 and get a return value. Then determine whether data read is normal according to the return value. print("The sumCnt is : %d, \t chk : %d" % (sumCnt, chk)) if ( chk is dht.DHTLIB_OK ): #read DHT11 and get a return value. Then determine whether data read is normal according to the return value. print("DHT11,OK!") elif (chk is dht.DHTLIB_ERROR_CHECKSUM): #data check has errors print("DHTLIB_ERROR_CHECKSUM!!") elif (chk is dht.DHTLIB_ERROR_TIMEOUT): #reading DHT times out print("DHTLIB_ERROR_TIMEOUT!") else: #other errors print("Other error!") print("Humidity : %.2f, \t Temperature : %.2f \n" % (dht.humidity, dht.temperature)) time.sleep(3)
def update_local_data(*argc, **argv): dht = DHT.get_dht() if dht is None: return global hour_id if hour_id not in local_data.keys(): local_data[hour_id] = [dht] else: local_data[hour_id].append(dht) #if it is the first hour, the avg_tmp and avg_hum #will be the average of all the data attain until now prev_hour_id = hour_id - 1 if prev_hour_id < 0: sum_tmp = 0 sum_hum = 0 cur_hour_len = len(local_data[hour_id]) if cur_hour_len <= 0: return for (tmp, hum) in local_data[hour_id]: sum_tmp += tmp sum_hum += hum cur_local_tmp = sum_tmp / cur_hour_len cur_local_hum = sum_hum / cur_hour_len avg_data[hour_id] = (cur_local_tmp, cur_local_hum) update_msg1(cur_local_tmp, cur_local_hum)
data = { "timestamp": date, "temperature": temperature, "humidity": humidity } requests.post(url=API_ENDPOINT, json=data) print(u"Date: {:s}, Temperature: {:g}\u00b0C, Humidity: {:g}%".format( date, temperature, humidity)) pi = pigpio.pi() if not pi.connected: print("pigpio not connected.") exit() s = DHT.sensor(pi, pin, model=sensor) tries = 1000 # try 1000 times if error while tries: try: timestamp, gpio, status, temperature, humidity = s.read( ) #read DHT device print("attempting: ", status) if (status == DHT.DHT_GOOD): output_data(timestamp, temperature, humidity) exit() # Exit after successful read if (status == DHT.DHT_TIMEOUT): # no response from sensor print("no response from sensor") #exit() time.sleep(2) tries -= 1
mosipin = SPIMOSI, cspin = SPICS, pinmode = PINMODE ) #configure thermistor therm = Thermistor(A=A, B=B, C=C, R_25C=R_25C, R_std=R_STD, adc=adc, adc_channel = ADC_CHANNEL ) #setup the DHT library DHT_PIN = 4 DHT.setup(pinmode='BCM') dht = DHT.DHT22(DHT_PIN) #setup thingspeak channel api_write_key = open('.API_WRITE_KEY.secret').read().strip() thingspeak_channel = ThingspeakChannel(api_write_key) #read thermistor in a loop try: while True: try: H_room, T_room = dht.read() #WARNING, this may occasionally throw an IOError T_soil = therm.read_temperature() print "---" print "timestamp: %s" % time.time()
import os import time import json from pprint import pprint import sys lcd = LCD.Create() lcd.Clear() ### #gsm.sendSMS("Starting..") #time.sleep(2) dht_sensors = [11, 19, 13, 12, 27, 26, 4] #dht_sensors = [4,26,27,22,10,19,11] print("Constructing DHT Sensors") dht = DHT.DHT_SENSOR(dht_sensors) cell1_dt = 23 cell1_sck = 24 cell2_dt = 8 cell2_sck = 25 cell3_dt = 16 cell3_sck = 20 cell1Swap = 'cell1.swp' cell2Swap = 'cell2.swp' cell3Swap = 'cell3.swp' print('Constructing Cell1') cell1 = loadCell.Create(cell1_dt, cell1_sck, swapFile=cell1Swap)
def rebalance(self, new_view, old_view, epoch_op): key_to_delete = '' global key_value_replica global data_in_view for [[addr, port], server_id] in new_view: try: sock = common_functions.create_connection( addr, port, port, 5, False) except Exception as e: print("Couldn't establish a connection with replica: ", e) common_functions.send_msg(sock, {'cmd': 'get_data'}, False) recvd_msg = common_functions.recv_msg(sock, False) if (recvd_msg is not None): for key, value in recvd_msg.items(): if (key not in data_in_view): with self.lock: data_in_view[key] = value sock.close() for key, value in data_in_view.items(): old_replicas = DHT.bucket_allocator(key, old_view) new_replicas = DHT.bucket_allocator(key, new_view) for [[addr, port], server_id] in new_replicas: try: sock = common_functions.create_connection( addr, port, port, 5, False) except Exception as e: print("Couldn't establish a connection with replica: ", e) common_functions.send_msg(sock, { 'cmd': 'get_data', 'key': key }, False) recvd_msg = common_functions.recv_msg(sock, False) if (recvd_msg is not None) or (recvd_msg != ''): key_value_replica = recvd_msg sock.close() with self.lock: # print (key_value_replica) try: new_key, new_value = key_value_replica if (new_key not in self.bucket): try: self.bucket[new_key] = new_value print("Adding {}:{} to current replica...".format( new_key, new_value)) except LookupError as e: print( "Couldn't set the key since there was no such key..." ) else: if (epoch_op == 'add'): if (old_view is not None): # print ("Old view: {}".format(old_view)) # print ("New view: {}".format(new_view)) # print ("unique_id: {}".format(self.unique_id)) for [[addr, port], server_id] in old_view: # print ("tuple: {}".format([[addr, port], server_id])) if (self.unique_id == server_id) and ([[ addr, port ], server_id] not in new_view): print( "Deleting {}:{} on old replica...". format(new_key, new_value)) key_to_delete = new_key try: del self.bucket[key_to_delete] except LookupError: print( "Couldn't delete the key since there was no such key..." ) except Exception as e: print("No key_value found: ", e)
def process_msg_from_client(self, recvd_msg): function_from_cmd = recvd_msg[ "cmd"] # takes function arguments from received dict try: unique_id = recvd_msg["id"] # takes unique_id from received dict except LookupError: unique_id = None # checks if function is print; if so, then take the text from the received dict if (function_from_cmd == "print"): text = recvd_msg["text"] # print's argument # text length will always be > 0; if text length == 1, # then make text into string rather than a list. if (len(text) == 1): text = text[0] print("Printing " + str(text)) response = {'status': 'success', 'result': text, 'id': unique_id} elif (function_from_cmd == "set"): server_rpc.set(recvd_msg["key"], recvd_msg["val"]) response = {'status': 'success', 'id': unique_id} elif (function_from_cmd == "get"): result = server_rpc.get(recvd_msg["key"]) if (result is None): response = { 'status': 'fail', 'result': result, 'id': unique_id } else: response = { 'status': 'success', 'result': result, 'id': unique_id } elif (function_from_cmd == "query_all_keys"): result = server_rpc.query_all_keys() if (result is None): response = { 'status': 'fail', 'result': result, 'id': unique_id } else: response = { 'status': 'success', 'result': result, 'id': unique_id } elif (function_from_cmd == "get_id"): # print ("Returning service_id to viewleader...".format(self.unique_id)) response = str(self.unique_id) elif (function_from_cmd == "getr"): with self.lock: key = recvd_msg["key"] try: response = { 'status': 'success', 'result': self.bucket[key], 'id': unique_id } except LookupError: response = { 'status': 'fail', 'result': '', 'id': unique_id } elif (function_from_cmd == "setr"): with self.lock: key = recvd_msg["key"] value = recvd_msg["val"] try: self.bucket[key] = value print("Stored {}:{} in this replica.".format(key, value)) response = {'status': 'success', 'id': unique_id} except LookupError: response = {'status': 'fail', 'id': unique_id} elif (function_from_cmd == "request_vote"): key = recvd_msg["key"] if (key not in self.in_commit_phase): self.in_commit_phase.append(key) # print ("Added key to in_commit_phase: {}".format(self.in_commit_phase)) viewleader_epoch = recvd_msg["epoch"] server_id = uuid.UUID(recvd_msg["server_id"]).hex response = self.vote(viewleader_epoch, server_id) else: print("Aborting because there is a pending commit...") response = 'abort' print("Sending vote back to client...") elif (function_from_cmd == "remove_commit"): try: key = recvd_msg["key"] except LookupError: print("No such key.") # print ("Keys in in_commit_phase: {}".format(self.in_commit_phase)) # print ("Key: {}".format(key)) try: self.in_commit_phase.remove(key) except ValueError: print("Key is not currently being committed.") response = {'status': 'success', 'id': unique_id} elif (function_from_cmd == "get_data"): try: key = recvd_msg["key"] try: response = (key, self.bucket[key]) except LookupError as e: response = '' except LookupError: response = self.bucket # print ("Couldn't find the key...") elif (function_from_cmd == "rebalance"): epoch_op = recvd_msg['op'] new_view = recvd_msg['new_view'] old_view = recvd_msg['old_view'] for key, value in self.bucket.items(): old_replicas = DHT.bucket_allocator(key, old_view) new_replicas = DHT.bucket_allocator(key, new_view) thread = threading.Thread(target=self.rebalance, args=(new_view, old_view, epoch_op)) thread.start() response = '' else: print("Rejecting RPC request because function is unknown.") return response
import wiringpi import DHT import time import datetime #print("gunwo") instance = DHT.DHT11(6) #print("shieeeeet") 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) #else: print("oneoneone") time.sleep(0.5) except KeyboardInterrupt: print("Cleanup") GPIO.cleanup()
from DHT import * from HCR import * from PIR import * from File import * import os import time newDHT = DHT() newHCR = HCR() newPIR = PIR() newFile = File() array = [] newFile.readData("Respaldo") try: while True: if os.path.isfile("Respaldo2.txt"): #print("Existe") file = open("Respaldo2.txt", "a") else: #print("No existe") file = open("Respaldo2.txt", "w") newDHT.leerTemperatura() newDHT.guardarDatosSQL() newDHT.guardarDatosMongo() #print(newDHT.retornarDatos()) newPIR.leerPrescencia() newPIR.guardarDatosPIRSQL() newPIR.guardarDatosPIRMongo() #print(newPIR.retornarDatosPIR()) newHCR.leerDistancia() newHCR.guardarDatosSQL() newHCR.guardarDatosMongo()
ap.add_argument("gpio", nargs="+", type=int) args = ap.parse_args() sbc = rgpio.sbc() if not sbc.connected: exit() chip = sbc.gpiochip_open(args.gpiochip) # Instantiate a class for each GPIO S = [] for g in args.gpio: s = DHT.sensor(sbc, chip, g) S.append(s) # save class while True: try: for s in S: d = s.read() print("{:.3f} g={:2d} s={} t={:3.1f} rh={:3.1f}".format( d[0], d[1], d[2], d[3], d[4])) time.sleep(2) except KeyboardInterrupt: break for s in S: s.cancel()
""" Instantiate a class for each GPIO # for testing use a GPIO+100 to mean use the callback S = [] for i in range(0, argc): # ignore first argument which is command name g = int(DHT_list[i]) if (g >= 100): s = DHT.sensor(pi, g-100, callback=callback) else: s = DHT.sensor(pi, g) S.append((g, s)) # store GPIO and class """ while True: try: S = [] s = DHT.sensor(pi, 4) S.append((4, s)) for s in S: d = s[1].read() temperature_01 = '{:3.1f}'.format((d[3])) humidity_01 = '{:3.1f}'.format((d[4])) S = [] s = DHT.sensor(pi, 18) S.append((18, s)) for s in S: d = s[1].read() temperature_02 = '{:3.1f}'.format((d[3])) humidity_02 = '{:3.1f}'.format((d[4])) sensordata = "/dev/shm/dht22_data.raw"
if argc < 2: print("Need to specify at least one GPIO") exit() pi = pigpio.pi() if not pi.connected: exit() # Instantiate a class for each GPIO # for testing use a GPIO+100 to mean use the callback S = [] for i in range(1, argc): # ignore first argument which is command name g = int(sys.argv[i]) if (g >= 100): s = DHT.sensor(pi, g - 100, callback=callback) else: s = DHT.sensor(pi, g) S.append((g, s)) # store GPIO and class while True: try: for s in S: if s[0] >= 100: s[1].read() # values displayed by callback else: d = s[1].read() print("{:.3f} {:2d} {} {:3.1f} {:3.1f}".format( d[0], d[1], d[2], d[3], d[4])) time.sleep(2) except KeyboardInterrupt:
def __init__(self): threading.Thread.__init__(self) self.temp = 0 self.humid = 0 self.instance = DHT.DHT11(6)