Ejemplo n.º 1
0
def main():
    loop = asyncio.new_event_loop()
    dht.DHT(loop)
    try:
        loop.run_forever()
    finally:
        loop.close()
    pass
Ejemplo n.º 2
0
    Address('127.0.0.1', addr)
    for addr in list(set([random.randrange(40000, 50000) for x in range(10)]))
]
for a in address_list:
    print(a.__str__())
# keep unique ones
address_list = list(set(address_list))
# hash the addresses
hash_list = [addr.__hash__() for addr in address_list]
hash_list.sort()
# create the nodes
locals_list = []
for i in range(0, len(address_list)):
    try:
        if len(locals_list) == 0:
            local = dht.DHT(address_list[i])
        else:
            # use a random already created peer's address
            # as a remote
            local = dht.DHT(
                address_list[i], locals_list[random.randrange(
                    len(locals_list))].local_.address_)
    except socket.error:  # socket bussy
        del hash_list[address_list[i].__hash__()]
    #local.local_.start()
    locals_list.append(local)
    time.sleep(0.1)

# We need to give it some time to stabilize
time.sleep(20)
Ejemplo n.º 3
0
Archivo: dg.py Proyecto: Daiver/jff
        '''try:
            old = dht[k]
        except Exception as e:
            print 'ERR1', k, e
            old = []
        v += old'''
        #if k:
        #print k
        #    dht[k] = v
    print 'Checking...'
    #for k, v in freq.iteritems():
    #    if k:
    #        check(k, v)
            
if __name__ == '__main__':
    cr = crawler.Crawler()
    print 'creating dht'
    #dht = pydht.DHT("127.0.0.1",6111, boot_host="127.0.0.1", boot_port=5001)
    dht = pydht.DHT("127.0.0.1", 6000, "127.0.0.1", 6101)
    print 'grabbing...'
    #freq = cr.grabFromPage('http://habrahabr.ru',2, dht)
    #freq, urls = cr.grabFromPage('http://www.cs.vsu.ru/~svv/',3, {}, True)
    #freq, urls = cr.grabFromPage('http://www.cs.vsu.ru/~svv/lectures.html',3, dht, True)
    print 'adding index'
    #shareIndex(dht, freq)
    #print urls
    while 1:
        s = raw_input('>')
        #print activate(freq, s)
        print activate(dht, s)
Ejemplo n.º 4
0
    settings = dict((k, v.value()) for k, v in options.items())

    ip_ports = [('202.177.254.130', 43251), ('71.7.233.108', 40641),
                ('189.223.55.147', 54037), ('186.213.54.11', 57479),
                ('85.245.177.29', 58042), ('2.81.68.199', 37263),
                ('188.24.193.27', 15796), ('210.252.33.4', 39118),
                ('175.143.215.38', 56067), ('95.42.100.15', 34278),
                ('211.224.26.47', 25628), ('92.6.154.240', 48783),
                ('173.255.163.104', 52159), ('2.10.206.61', 12815),
                ('187.123.98.253', 58901), ('83.134.13.212', 10770),
                ('78.139.207.123', 50045), ('125.25.191.209', 56548),
                ('71.234.82.146', 14973), ('72.207.74.219', 14884),
                ('79.136.190.188', 50634), ('72.80.103.198', 36823),
                ('77.122.72.44', 56554)]

    dht = dht.DHT(51414, ip_ports)

    frontend_routes = [
        ('/?', IndexHandler),
    ]
    frontend_application = tornado.web.Application(frontend_routes, **settings)
    frontend_server = tornado.httpserver.HTTPServer(frontend_application,
                                                    io_loop=ioloop)
    frontend_server.bind(options.frontend_port, '')
    frontend_server.start()

    IndexHandler.register_dht(dht)

    dht.bootstrap()
    dht.start()
Ejemplo n.º 5
0
        motion = "No movement detected"
        print motion
        with open('/usr/local/bin/motion', 'w') as file:
            file.write(motion)
        time.sleep(3)

    elif i == 1:  #When output from motion sensor is HIGH
        GPIO.output(26, GPIO.HIGH)
        motion = "Movement detected"
        print motion
        with open('/usr/local/bin/motion', 'w') as file:
            file.write(motion)
        time.sleep(5)

    try:
        instance = dht.DHT(pin=PIN2, sensor=11)
        result = instance.read()
        if result.is_valid():
            ho = result.humidity
            print ho
            to = result.temperature
            print to
            if (to >= 30):
                GPIO.output(22, GPIO.HIGH)
                with open('/usr/local/bin/fan', 'w') as file:
                    file.write('on')
                if (send_mail == 0):
                    set_mail(mailmsg)
                    send_mail = 1

            else:
Ejemplo n.º 6
0
def read_and_output_sensor_data(sensor_cfg):
    if sensor_cfg.verbose:
        print 'Sensor: ' , sensor_cfg.sensor_type
        if not sensor_cfg.sensor_param == '':
            print 'Parameter: ' + sensor_cfg.sensor_param
        if sensor_cfg.out_channel == config.CSV_FILE_CHANNEL:
            print 'CSV file channel'
            print 'CSV file: ', sensor_cfg.out_file
        if sensor_cfg.out_channel == config.MQTT_CHANNEL:
            print 'MQTT channel'
            print 'Config file: ', sensor_cfg.mqtt_cfg_file
        if sensor_cfg.out_file is not None:
            print 'Output file  : ', sensor_cfg.out_file
            print 'Output format: ', sensor_cfg.out_format

    sens = None

    if sensor_cfg.sensor_type.lower() == 'dummy':
        import sensor
        sens = sensor.DummySensor(
            id=sensor_cfg.id,
            label=sensor_cfg.label)
    elif sensor_cfg.sensor_type.lower() == 'bmp085':
        import bmp085
        sens = bmp085.BMP085Sensor(
            param=sensor_cfg.sensor_param,
            id=sensor_cfg.id,
            label=sensor_cfg.label,
            verbose=sensor_cfg.verbose)
    elif sensor_cfg.sensor_type.lower() == 'dht11':
        import dht
        sens = dht.DHT(
            sensor_type='11',
            pin=sensor_cfg.sensor_param,
            id=sensor_cfg.id,
            label=sensor_cfg.label,
            verbose=sensor_cfg.verbose)
    elif sensor_cfg.sensor_type.lower() == 'dht22':
        import dht
        sens = dht.DHT(
            sensor_type='22',
            pin=sensor_cfg.sensor_param,
            id=sensor_cfg.id,
            label=sensor_cfg.label,
            verbose=sensor_cfg.verbose)
    elif sensor_cfg.sensor_type.lower() == 'dht2302':
        import dht
        sens = dht.DHT(
            sensor_type='2302',
            pin=sensor_cfg.sensor_param,
            id=sensor_cfg.id,
            label=sensor_cfg.label,
            verbose=sensor_cfg.verbose)
    elif sensor_cfg.sensor_type.lower() == 'htu21':
        import htu21d
        sens = htu21d.HTU21Sensor(
            param=sensor_cfg.sensor_param,
            id=sensor_cfg.id,
            label=sensor_cfg.label,
            verbose=sensor_cfg.verbose)
    elif sensor_cfg.sensor_type.lower() == 'ds1820':
        import ds1820
        sens = ds1820.DS1820Sensor(
            sens_id=sensor_cfg.sensor_param,
            id=sensor_cfg.id,
            label=sensor_cfg.label,
            verbose=sensor_cfg.verbose)

    if sens is not None:
        if sensor_cfg.out_channel == config.MQTT_CHANNEL:
            channel = outchannel.MqttChannel(
                mqtt_cfg_file=sensor_cfg.mqtt_cfg_file,
                hostname=sensor_cfg.hostname,
                verbose=sensor_cfg.verbose)
        elif (sensor_cfg.out_channel == config.FILE_CHANNEL) \
                and (sensor_cfg.out_file is not None):
            channel = outchannel.FileChannel(
                out_format=sensor_cfg.out_format,
                fn=sensor_cfg.out_file,
                verbose=sensor_cfg.verbose)
        elif sensor_cfg.out_channel == config.CSV_FILE_CHANNEL:
            channel = outchannel.CSVFileChannel(
                fn=sensor_cfg.out_file,
                verbose=sensor_cfg.verbose)
        else:
            channel = outchannel.ConsoleChannel(
                out_format=sensor_cfg.out_format)

        channel.output(sens)
    else:
        print 'Unsupported sens ', sensor_cfg.sensor_type
Ejemplo n.º 7
0
def benchmark_dht(num_peers: int, initial_peers: int, num_experts: int,
                  expert_batch_size: int, random_seed: int,
                  wait_after_request: float, wait_before_read: float,
                  wait_timeout: float, expiration: float):
    random.seed(random_seed)

    print("Creating peers...")
    peers = []
    for _ in trange(num_peers):
        neighbors = [
            f'0.0.0.0:{node.port}'
            for node in random.sample(peers, min(initial_peers, len(peers)))
        ]
        peer = dht.DHT(initial_peers=neighbors,
                       start=True,
                       wait_timeout=wait_timeout,
                       expiration=expiration,
                       listen_on=f'0.0.0.0:*')
        peers.append(peer)

    store_peer, get_peer = peers[-2:]

    expert_uids = list(
        set(f"expert.{random.randint(0, 999)}.{random.randint(0, 999)}.{random.randint(0, 999)}"
            for _ in range(num_experts)))
    print(f"Sampled {len(expert_uids)} unique ids (after deduplication)")
    random.shuffle(expert_uids)

    print(f"Storing peers to dht in batches of {expert_batch_size}...")
    successful_stores = total_stores = total_store_time = 0
    benchmark_started = time.perf_counter()
    endpoints = []

    for start in trange(0, num_experts, expert_batch_size):
        store_start = time.perf_counter()
        endpoints.append(random_endpoint())
        success_list = store_peer.declare_experts(
            expert_uids[start:start + expert_batch_size], endpoints[-1])
        total_store_time += time.perf_counter() - store_start

        total_stores += len(success_list)
        successful_stores += sum(success_list)
        time.sleep(wait_after_request)

    print(
        f"Store success rate: {successful_stores / total_stores * 100:.1f}% ({successful_stores} / {total_stores})"
    )
    print(
        f"Mean store time: {total_store_time / total_stores:.5}, Total: {total_store_time:.5}"
    )
    time.sleep(wait_before_read)

    if time.perf_counter() - benchmark_started > expiration:
        warn(
            "Warning: all keys expired before benchmark started getting them. Consider increasing expiration_time"
        )

    successful_gets = total_get_time = 0

    for start in trange(0, len(expert_uids), expert_batch_size):
        get_start = time.perf_counter()
        get_result = get_peer.get_experts(expert_uids[start:start +
                                                      expert_batch_size])
        total_get_time += time.perf_counter() - get_start

        for i, expert in enumerate(get_result):
            if expert is not None and expert.uid == expert_uids[start + i] \
                    and expert.endpoint == endpoints[start // expert_batch_size]:
                successful_gets += 1

    if time.perf_counter() - benchmark_started > expiration:
        warn(
            "Warning: keys expired midway during get requests. If that is not desired, increase expiration_time param"
        )

    print(
        f"Get success rate: {successful_gets / len(expert_uids) * 100:.1f} ({successful_gets} / {len(expert_uids)})"
    )
    print(
        f"Mean get time: {total_get_time / len(expert_uids):.5f}, Total: {total_get_time:.5f}"
    )

    alive_peers = [peer.is_alive() for peer in peers]
    print(f"Node survival rate: {len(alive_peers) / len(peers) * 100:.3f}%")
Ejemplo n.º 8
0
Archivo: webapp.py Proyecto: Daiver/jff
from flask import Flask
from flask import request
app = Flask(__name__)
import dht as pydht

dht = pydht.DHT("127.0.0.1", 6000, "127.0.0.1", 8088)
head = '''
        <h2 align=center>Search</h2>
        <form action="/search/" method="post" align=center>
            <input name="q" value=%s></input>
            <input type=submit />
        </form></br>
    '''

css = '''
    <html>
        <head>
        </head>
    <body>
'''


@app.route('/dn/<page>')
def show_user_profile(page):
    # show the user profile for that user
    if page not in dht:
        return "<h2>404</h2><h3>%s not found</h3>" % page
    return dht[page]


if __name__ == "__main__":
Ejemplo n.º 9
0
import sys
import dht as pydht

if __name__ == '__main__':
    port, url, file = sys.argv[1:4]
    force = len(sys.argv) > 4
    print 'creating dht'
    dht = pydht.DHT("127.0.0.1", int(port), "127.0.0.1", 6100)
    #freq, urls = cr.grabFromPage('http://www.cs.vsu.ru/~svv/lectures.html',3, dht, True)
    if url not in dht or force:
        print str(open(file).read())
        dht[url] = str(open(file).read())
    else:
        print 'url in base'

Ejemplo n.º 10
0
        f = open(path)
        l = ast.literal_eval(f.read())
        ip_ports = ip_ports + l

    #print ip_ports

    #开始端口
    start_port = 51414
    #节点数
    count = 1

    dht_list = []
    for i in range(count):
        #23649f6ace4b4062879066a6afe99b91c1880b8f
        dht0 = dht.DHT(
            start_port + i,
            ip_ports,
            node_id="23649f6ace4b4062879066a6afe99b91c1880b8f".decode('hex'))
        dht_list.append(dht0)

    #dht = dht.DHT(51414, ip_ports, node_id='d54408eb2a5d686bd3e587f7a96c2facebbeadfc'.decode('hex'))

    frontend_routes = [
        ('/c', IndexHandler),
        ('/a', AHandler),
        ('/b', BHandler),
        ('/dump', DumpHandler),
        ('/dumppeers', DumpPeersHandler),
        ('/dumpmem', DumpMemHandler),
    ]
    frontend_application = tornado.web.Application(frontend_routes, **settings)
    frontend_server = tornado.httpserver.HTTPServer(frontend_application,
Ejemplo n.º 11
0
import glob
import MySQLdb
from pyA20.gpio import gpio
from pyA20.gpio import port
import dht
from time import strftime
 

code = 'dth11-temp'

# initialize GPIO
PIN2 = port.PA6
gpio.init()
 
# read data using pin
instance = dht.DHT(pin=PIN2)

# Variables for MySQL
db = MySQLdb.connect(host="localhost", user="******",passwd="password", db="HN_database")
cur = db.cursor()
 
def tempRead():
    result = instance.read()
    if result is None:
        return None
    if result.temperature is not None and result.humidity is not None:
        return round(result.temperature, 1), round(result.humidity, 1)
    else:
        return None
 
Ejemplo n.º 12
0
#!/usr/bin/python
import RPi.GPIO as GPIO
import dht
import time
import datetime

# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.cleanup()

# read data using pin 14

def doit(obj, retry=5000, file='/tmp/dht22'):
	for x in range(0, retry):
		result = obj.read()
		if result.is_valid():
			cas=str(datetime.datetime.now())[:16]
			f = open(file, 'a')
			#print("pokus c.: " + str(x))
			values = (str(cas) + ", " + str(result.temperature) + ", " + str(result.humidity) + "\n")
			f.write(values)
			f.close()
			break

instance = dht.DHT(pin=5, sensor="DHT22")
instance1 = dht.DHT(pin=7, sensor="DHT22")
doit(file='/home/sensor/th.csv', obj=instance)
doit(file='/home/sensor/th1.csv', obj=instance1)
Ejemplo n.º 13
0
    log.write("\n\n\n\n")

    peermgr = PeerManager(log)

    threads = []

    # start HTTP server for JSON-RPC
    rpcexec = rpc.RPCExec(peermgr, log, settings['rpcuser'],
                          settings['rpcpass'])
    rpcserver = gevent.pywsgi.WSGIServer(('', settings['rpcport']),
                                         rpcexec.handle_request)
    t = gevent.Greenlet(rpcserver.serve_forever)
    threads.append(t)

    dht = dht.DHT(log, settings['dhtport'], NODE_ID)
    threads.append(dht)

    if ('dht_add_host' in settings and 'dht_add_port' in settings):
        dht.add_node(settings['dht_add_host'], settings['dht_add_port'])

    if settings['listen']:
        p2pserver = NodeServer(settings['listen_host'],
                               settings['listen_port'], log, peermgr)

        threads.append(p2pserver)

    # connect to specified remote node
    if addnode:
        c = peermgr.add(settings['host'], settings['port'])
        threads.append(c)
Ejemplo n.º 14
0
from acmepins import GPIO
import dht
import time
import datetime

instance = dht.DHT(pin='PC0')

result = instance.read()
if result.is_valid():
    print("Temperature: %d C" % result.temperature)
    print("Humidity: %d %%" % result.humidity)
else:
    print("Sensor reading failure")
Ejemplo n.º 15
0
import RPi.GPIO as GPIO
import dht
import time
import datetime

# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

# read data using pin 4
instance = dht.DHT(pin=4)

while True:
    result = instance.read()
    if result.is_valid():
        print("Last valid input: " + str(datetime.datetime.now()))
        print("Temperature: %f C" % result.temperature)
        print("Humidity: %f %%" % result.humidity)
    else:
        print("Error: %d" % result.error_code)
    time.sleep(3)