Beispiel #1
0
def scenario1():
    SIMULATION_LOOP = 10000

    SATISFACTION_THRESHOLD = 0.8

    # Temperature value
    TARGET_TEMP_VAL = 20
    ERR_TEMP_VAL = 1

    # Declare sensors
    sensors = []
    sensor1 = sensor("sensor1")
    sensors.append(sensor1)
    sensor2 = sensor("sensor2")
    sensors.append(sensor2)
    sensor3 = sensor("sensor3")
    sensors.append(sensor3)

    # Declare temperature feature
    temp_sensor1 = feature_temperature(TARGET_TEMP_VAL, ERR_TEMP_VAL)
    temp_sensor2 = feature_temperature(TARGET_TEMP_VAL, ERR_TEMP_VAL * 2)
    temp_sensor3 = feature_temperature(TARGET_TEMP_VAL, ERR_TEMP_VAL * 4)

    sensor1.add_feature(temp_sensor1)
    sensor2.add_feature(temp_sensor2)
    sensor3.add_feature(temp_sensor3)

    # Configure satisfaction evaluator
    temp_satisfaction_eval = satisfaction_temperature(TARGET_TEMP_VAL)

    # Configure feature weights
    feature_weights = {feature_type.TEMPERATURE: 1}

    # Create naive bayes reputation model
    nb = {}
    for sensor_item in sensors:
        nb[sensor_item.get_name()] = naive_bayes(sensor_item.get_name(), feature_weights, SATISFACTION_THRESHOLD)

        # Add satisfaction evaluator to NB model
        nb[sensor_item.get_name()].add_satisfaction(temp_satisfaction_eval)

    for i in range(0, SIMULATION_LOOP):    
        for sensor_item in sensors:        
            # Generate sensor data        
            data = sensor_item.get_data()
            nb[sensor_item.get_name()].compute(data)
            nb[sensor_item.get_name()].save_reputation()

    # Plot the reputation probability
    legend = []
    for sensor_item in sensors:
        legend.append(sensor_item.get_name())
        plt.plot(nb[sensor_item.get_name()].get_reputation_history([feature_type.TEMPERATURE]))

    plt.xlabel("Steps")
    plt.ylabel("Trust reputation probability")
    plt.legend(legend)
    plt.show()
    def image_callback(self, msg):
        # BEGIN BRIDGE
        image = self.bridge.imgmsg_to_cv2(msg)
        #cv2.imshow("ori", image )
        # END BRIDGE
        # BEGIN HSV
        hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
        #cv2.imshow("hsv", hsv )
        # END HSV
        # BEGIN FILTER
        lower_green = numpy.array([35, 43, 46])
        upper_green = numpy.array([77, 255, 255])
        mask = cv2.inRange(hsv, lower_green, upper_green)
        # END FILTER
        masked = cv2.bitwise_and(image, image, mask=mask)
        #cv2.imshow("res", mask )

        f_x = (2.8 / 3.984) * 160
        f_y = (2.8 / 2.952) * 120
        c_x = 160 * 0.5
        c_y = 120 * 0.5
        img = sensor()
        img = image
        for tag in img.find_apriltags(fx=f_x, fy=f_y, cx=c_x, cy=c_y):
            img.draw_rectangle(tag.rect(), color=(255, 0, 0))
            img.draw_cross(tag.cx(), tag.cy(), color=(0, 255, 0))
            print_args = (tag.x_translation(), tag.y_translation(), tag.z_translation(), \
                degrees(tag.x_rotation()), degrees(tag.y_rotation()), degrees(tag.z_rotation()))
            print("Tx: %f, Ty %f, Tz %f, Rx %f, Ry %f, Rz %f" % print_args)

        cv2.imshow("window", img)
        cv2.waitKey(3)
def experiment_nine(id, sensors, subfolder):
    '''
    Sets up NetworkTopo9.
    :param id: (Incremental) Identifier of the experiment
    :param sensors: list of boolean values telling which sensors have to be used
    :return: Saves the topology stored in the ledger in a file called print_topo[id].png
    '''
    servers = start_blockchain()
    (net, topo) = start_network_number(9,
                                       sensor1=sensors[0],
                                       sensor2=sensors[1],
                                       sensor3=sensors[2],
                                       sensor4=sensors[3])
    os.system('./init.sh')
    topo.create_alias_file()
    asnames = topo.active_sensors
    psnames = topo.passive_sensors
    msnames = topo.monitor_sensors
    sensors = []
    startup(len(msnames), msnames, net)
    ips = get_responding_ips(msnames)
    topo.add_firewall_rules(net)
    clean_cmd_base = 'rm -rf traceroute/'
    for i in range(len(psnames)):
        clean_cmd = [clean_cmd_base + msnames[i] + '/*']
        os.system('mkdir traceroute/' + msnames[i])
        sensors.append(
            sensor(psnames[i],
                   len(msnames),
                   net,
                   'configuration/sensor_config' + str(i + 1) + '.json',
                   hosts=msnames,
                   max_fail=3,
                   clean_cmd=clean_cmd,
                   known_ips=ips,
                   simulation=True,
                   sleep_time=30,
                   subnets='192.168.0.0/16 or 12.0.0.0/8',
                   verbose=False,
                   asid=asnames[i],
                   msid=msnames[i],
                   include_hosts=True,
                   intf=topo.interface_name[i]))
    [s.start() for s in sensors]
    hosts = [
        net['h1'], net['h2'], net['h3'], net['h4'], net['h5'], net['h6'],
        net['h7'], net['h8']
    ]
    net['h3'].cmd('ping -c 1 -W 1 ' + net['h1'].IP())
    net['h4'].cmd('ping -c 1 -W 1 ' + net['h1'].IP())
    time.sleep(10)
    print '\n\n ...............  PINGING   .............. \n\n'
    net.ping(hosts=hosts)
    time.sleep(200)
    [s.stop() for s in sensors]
    [s.wait_end() for s in sensors]
    servers[3].draw_topology(prefix='topo_exp9/' + subfolder + '/',
                             suffix=str(id))
    stop_blockchain(servers)
 def get_sensors_list(self):
     sensors_list = []
     url = "http://" + self.ip + ":" + self.port + "/sensors/get_sensors_list"
     response = urllib.urlopen(url)
     sensors_dict = json.loads(response.read())
     sensors_id_list = sensors_dict.keys()
     for sensor_id in sensors_id_list:
         if (sensors_dict[sensor_id] != ""):  # look if the node is empty
             sensors_list.append(sensor(self.ip, self.port, sensor_id))
     return sensors_list
def experiment_one(id):
    '''
    Sets up NetworkTopo1 with two sensors.
    :param id: (Incremental) Identifier of the experiment
    :return: Saves the topology stored in the ledger in a file called print_topo[id].png
    '''
    servers = start_blockchain()
    (net, topo) = start_network_number(1, sensor1=True, sensor2=True)
    os.system('./init.sh')
    topo.create_alias_file()
    asnames = topo.active_sensors
    psnames = topo.passive_sensors
    msnames = topo.monitor_sensors
    startup(2, msnames, net)
    ips = get_responding_ips(msnames)
    sensors = []
    clean_cmd_base = 'rm -rf traceroute/'
    for i in range(len(psnames)):
        clean_cmd = [clean_cmd_base + msnames[i] + '/*']
        os.system('mkdir traceroute/' + msnames[i])
        sensors.append(
            sensor(psnames[i],
                   len(msnames),
                   net,
                   'configuration/sensor_config' + str(i + 1) + '.json',
                   hosts=msnames,
                   max_fail=3,
                   clean_cmd=clean_cmd,
                   known_ips=ips,
                   simulation=True,
                   verbose=False,
                   asid=asnames[i],
                   msid=msnames[i],
                   include_hosts=True,
                   intf=psnames[i] + '-eth0'))
    [s.start() for s in sensors]
    #CLI(net)
    time.sleep(10)
    # Ping toward the sensor on the other subnet
    hosts = [net['h3'], net['h4'], net['h5'], net['h1'], net['h2'], net['h0']]
    net.ping(hosts=hosts)
    '''
    net['h3'].cmd('ping -c 1 192.168.1.102 ')  # hps1
    net['h4'].cmd('ping -c 1 192.168.1.102 ')  # hps1
    net['h5'].cmd('ping -c 1 192.168.1.102 ')  # hps1
    net['h1'].cmd('ping -c 1 192.168.2.102 ')  # hps2
    net['h2'].cmd('ping -c 1 192.168.2.102  ')  # hps2
    net['h0'].cmd('ping -c 1 192.168.2.102  ')  # hps2
    '''
    time.sleep(120)
    [s.stop() for s in sensors]
    servers[3].draw_topology(prefix='topo_exp1/', suffix=str(id))
    stop_blockchain(servers)
Beispiel #6
0
def start_net():
    ''' Start Mininet Topology'''
    topo = NetworkTopo()
    net = Mininet(topo=topo)
    add_static_routes(net)
    net.start()
    s = sensor('h11',
               5,
               net,
               'file_config_prova/client1_config.json',
               max_fail=3,
               known_ips=['192.168.1.4', '192.168.12.2', '192.168.1.2'],
               simulation=True,
               readmit=False)
    s.start()
    time.sleep(10)
    h11 = net['h11']
    h21 = net['h21']
    h61 = net['h61']
    h71 = net['h71']
    net.pingAll()
    #net.interact()
    return net
Beispiel #7
0
from sensor import *
from threading import *
import serial.tools.list_ports

#port_list = list(serial.tools.list_ports.comports())
#for i in port_list:
#    print(i.device)



light = sensor()
light.init()
light.start()
print("here.")
Beispiel #8
0
 def __init__(self, sensorsConfig):
     sensor = sensor.sensor
     self.sensorMap = {}
     for port, sensorConfig in sensorsConfig.iteritems():
         self.sensorMap[port] = sensor(port, sensorConfig[1],
                                       sensorConfig[2])
Beispiel #9
0
	def __init__(self,initVal):
		self.sensor=sensor(zeros(10))#initialize it to zero
		self.rotation=quaternion(initVal)
Beispiel #10
0
 def __init__(self, adc, channel, sensitivity):
     self.sensor = sensor(adc, channel, "microphone")
     self.sensitivity = sensitivity
Beispiel #11
0
        <nt> = number of threads to be used to collect traces\n     
        <hosts> = sequence of hosts, separated by whitespace, that
        each thread will use deterministically\n"""
        sys.exit()
    (net, topo) = start_network_number(1)
    # Delete previously generated files..
    os.system('./init.sh')
    (nt, hosts) = parse_cmd_line()
    # Spawn the threads that will run iTop and store the topology induced from each thread in the Blockchain
    startup(nt, topo.sensors)
    ips = get_responding_ips(hosts)
    # Start one sensor
    s = sensor('r3',
               5,
               net,
               'sensor_config.json',
               max_fail=3,
               known_ips=ips,
               simulation=True,
               verbose=False)
    s.start()
    raw_input("\n\nPress any key when you want to tear down R5\n\n")
    print '\nTearing down router R5...\n'
    block_router(net, 'r5')
    raw_input("\n\nPress any key when you want to run again R5\n\n")
    unblock_router(net, 'r5')
    time.sleep(5)
    net.pingAll()
    raw_input("\n\nPress any key when you want to quit\n\n")
    s.stop()
Beispiel #12
0
	def __init__(self, adc, channel, sensitivity):
		self.sensor = sensor(adc, channel, "pressure")
		self.sensitivity = sensitivity
Beispiel #13
0
 def test_sensor_activated(self):
     self.assertEqual(sensor(mockMotionSensor), "Motion detected!")
Beispiel #14
0
import sys
from database import *
# from keyboard import *
from player import player
from recorder import *
from sensor import *

(cur,con)= initializeDB()
# make sure database memorology exist

record = None
# recorder thread
play = None
# player thread
reader = sensor()
reader.init()
reader.start()
#keyboard = keyboard()
#keyboard.init()
#keyboard.start()

while True:
    if play != None:
    # if player is already activated
        try:
            # 已经开始播放的情况 detect是否录音已播放完毕
            if not play.ifdo:
            # 不用再play了
                play.stop()
                play.join()
                print("join player successful")
def experiment_ten(id, sensors, subfolder):
    '''
    Sets up NetworkTopo9 with pattern=Tree..
    :param id: (Incremental) Identifier of the experiment
    :param sensors: list of boolean values telling which sensors have to be used
    :param subfolders: tells in which subfolder to store the drawing of the topology
    :return: Saves the topology stored in the ledger in a file called print_topo[id].png
    '''
    servers = start_blockchain()
    (net, topo) = start_network_number(9,
                                       sensor1=sensors[0],
                                       sensor2=sensors[1],
                                       sensor3=sensors[2],
                                       sensor4=sensors[3])
    os.system('./init.sh')
    topo.create_alias_file()
    asnames = topo.active_sensors
    psnames = topo.passive_sensors
    msnames = topo.monitor_sensors
    sensors = []
    topo.add_firewall_rules(net)
    # Here we skip the preliminary traces gathered by the sensors
    compute_distances(net, msnames)
    clean_cmd_base = 'rm -rf traceroute/'
    child_IP = {
        's1': '',
        's2': '192.168.4.2',
        's3': '192.168.5.2',
        's4': '192.168.5.2'
    }  # Each sensor has a different child_IP. Knowledge about the topology is exploited here
    for i in range(len(psnames)):
        clean_cmd = [clean_cmd_base + msnames[i] + '/*']
        os.system('mkdir traceroute/' + msnames[i])
        sensors.append(
            sensor(psnames[i],
                   len(msnames),
                   net,
                   'configuration/sensor_config' + str(i + 1) + '.json',
                   hosts=msnames,
                   max_fail=3,
                   clean_cmd=clean_cmd,
                   known_ips=[],
                   simulation=True,
                   sleep_time=30,
                   subnets='192.168.0.0/16 or 12.0.0.0/8',
                   verbose=False,
                   asid=asnames[i],
                   msid=msnames[i],
                   include_hosts=True,
                   intf=topo.interface_name[i],
                   nrr=False,
                   pattern='tree',
                   root_IP='12.10.5.1',
                   child_IP=child_IP[psnames[i]]))
        # root_IP is the IP address of r1. You could give a different IP for r1 based on which IP address the sensor (should) see, but it is the same..
    [s.start() for s in sensors]
    hosts = [
        net['h1'], net['h2'], net['h3'], net['h4'], net['h5'], net['h6'],
        net['h7'], net['h8'], net['r2'], net['r3']
    ]
    time.sleep(10)
    print '\n\n ...............  PINGING   .............. \n\n'
    net.ping(hosts=hosts, timeout=2)
    time.sleep(100)
    for s in sensors:
        s.impose_pattern()
    time.sleep(100)
    [s.stop() for s in sensors]
    [s.wait_end() for s in sensors]
    servers[3].draw_topology(prefix='topo_exp10/' + subfolder + '/',
                             suffix=str(id),
                             collapse=False)  #TODO messo collapse = false
    servers[3].store_topo_to_file('FINAL_TOPOLOGY')
    stop_blockchain(servers)
 def __init__(self, sensorsConfig):
     sensor = sensor.sensor
     self.sensorMap = {}
     for port, sensorConfig in sensorsConfig.iteritems():
         self.sensorMap[port] = sensor(port, sensorConfig[1], sensorConfig[2])
Beispiel #17
0
# My imports
from settings import *
from clockTile import *
from sensor import *
from writeValue import *
from brentCrude import *

# Setup all sensores
outdoorTemperature = sensor(100, "outdoorTemperature.csv", 24)
bedroomTemperature = sensor(101, "bedroomTemperature.csv", 24)
brentCrudeTicker = sensor("brentCrude", "brentCrude.csv", 24)

# Import data from sensors
outdoorTemperature.importData()
bedroomTemperature.importData()
brentCrudeTicker.importData()

# Variables for the time
thisMinute = datetime.datetime.now()
thisTenMinute = datetime.datetime.now()
thisHour = datetime.datetime.now()


while True:

	# Every Minute
	if datetime.datetime.now() >= thisMinute:
		thisMinute = datetime.datetime.now() + datetime.timedelta(minutes=1)

		# Read Sensor data
		outdoorTemperature.readData()
Beispiel #18
0
    net[r].cmd(cmd1)
    net[r].cmd(cmd2)
    net[r].cmd(cmd3)
    print '\nUnBlocked router ' + net[r].IP()

if __name__ == '__main__':
    net = start_net()
    os.system('./init.sh')
    os.system('rm -f sensor.log > /dev/null') # Previous log deleted in this test, not in general case
    hosts = ['h11', 'h21', 'h31', 'h41', 'h42', 'h61', 'h62', 'h71']
    print '\nCollecting traces, running iTop, sending transactions to the Blockchain servers..\n'
    run(hosts)
    ips = get_responding_ips(hosts)
    # Start one sensor
    ignored = get_hosts_ips_from_traces(hosts)
    s = sensor('r3', 5, net, 'sensor_config.json', max_fail=3, ignored_ips = ignored, #In sensor.py era hard coded 'r2'
               known_ips=ips, simulation=True, verbose=False, active = False)
    s.start()
    raw_input("\n\nPress any key when you want to run R6\n\n")
    unblock_router(net, 'r6')
    print '\nSensor should discover the new router and run iTop with reduced selection of monitors\n'
    time.sleep(10)
    mhosts = []
    mhosts.append(net['h11'])
    mhosts.append(net['r6'])
    for h in range(10):
        time.sleep(1)
        net.ping(mhosts)
    raw_input("\n\nPress any key when you want to quit\n\n")
    s.stop()
    # Assertion: was fast iTop successfully run?
    run = False
Beispiel #19
0
import json
import time
import WorKit
import datetime
import requests
import functions
from sensor import *
from slackclient import SlackClient
from flask import Flask, g, jsonify, request, redirect

sc = SlackClient(WorKit.bot_token)
temperature = sensor("EMSENSORDEVICEFORMAT00000001", "temperature")
delta = datetime.timedelta(0, 30, 0)


#LOOPS
def message_loop():
    if sc.rtm_connect():
        while True:
            message = sc.rtm_read()
            interpret(message)
            time.sleep(1)
    else:
        print("Connection Failed, invalid token?")


def data_loop():
    while True:
        get_sensor_data(temperature, datetime.datetime.now())
        time.sleep(30)
Beispiel #20
0
                    ])

                for sensor_index in range(0, num_sensors):
                    init_for_sensor = []
                    init_cov_for_sensor = []
                    for target_counter in range(0, num_targets):
                        init_for_sensor.append([
                            x[target_counter] + np.random.normal(0, 5),
                            y[target_counter] + np.random.normal(0, 5),
                            np.random.normal(0, .1),
                            np.random.normal(0, .1)
                        ])
                        init_cov_for_sensor.append(np.array(init_covariance))

                    temp_sensor_object = sensor("POLICY_COMM_LINEAR",
                                                x_sensor[sensor_index],
                                                y_sensor[sensor_index])
                    # Create tracker object for each target
                    tracker_object = []
                    for i in range(0, num_targets):
                        tracker_object.append(
                            EKF_tracker(init_for_sensor[i],
                                        np.array(init_covariance), A, B, x_var,
                                        y_var,
                                        bearing_var))  # create tracker object
                    jpdaf_object = JPDAF_agent(tracker_object, .004, pd, 1E-5)
                    temp_sensor_object.set_tracker_objects(jpdaf_object)
                    s.append(temp_sensor_object)

                #Form fusion agent
                #################
                    x_var = t[0].x_var
                    y_var = t[0].y_var

                    tracker_object = []
                    for i in range(0, num_targets):
                        tracker_object.append(
                            EKF_tracker(init_for_smc[i],
                                        np.array(init_covariance), A, B, x_var,
                                        y_var,
                                        bearing_var))  #create tracker object
                        #smc_object = smc_tracker(A,B,x_var,y_var,bearing_var,1000,np.array(init_for_smc))

                    #create JPDAF-tracker too
                    jpdaf_object = JPDAF_agent(tracker_object, .004, pd, 1E-5)

                    s = sensor("POLICY_COMM_LINEAR"
                               )  # create sensor object (stochastic policy)
                    #s = sensor("CONS_V")
                    measure = measurement(
                        bearing_var)  #create measurement object

                    m = []
                    x_est = []
                    y_est = []
                    x_vel_est = []
                    y_vel_est = []
                    x_truth = []
                    y_truth = []
                    x_vel_truth = []
                    y_vel_truth = []
                    uncertainty = []
                    vel_error = []
# coding=utf-8
import sys
from sensor import *

#TODO va fatta interfaccia a modo, con parsing argomenti linea di comando usando modulo argparse.
# In particolare, va data la possibilità di specificare argomenti opzionali
if __name__ == '__main__':
    if len(sys.argv) != 4:
        print 'Usage: python start_sensor.py <sensor_id> <num_hosts> <config_file>'
        sys.exit(1)
    sid = sys.argv[1]
    nh = sys.argv[2]
    config = sys.argv[3]
    s = sensor(sid, nh, config)
    s.start()
Beispiel #23
0
def scenario6():
    SIMULATION_LOOP = 10000

    SATISFACTION_THRESHOLD = 0.8

    # Temperature value
    TARGET_TEMP_VAL = 20
    ERR_TEMP_VAL = 1

    # Humidity level value
    TARGET_HUMIDITY_VAL = 60
    ERR_HUMIDITY_VAL = 10

    # CO2 level value
    TARGET_CO2_VAL = 1000
    ERR_CO2_VAL = 40

    # Declare sensors
    sensors = []
    sensor1 = sensor("sensor1")
    sensors.append(sensor1)
    sensor2 = sensor("sensor2")
    sensors.append(sensor2)
    sensor3 = sensor("sensor3")
    sensors.append(sensor3)

    # Declare temperature feature
    temp_sensor1 = feature_temperature(TARGET_TEMP_VAL, ERR_TEMP_VAL)
    temp_sensor2 = feature_temperature(TARGET_TEMP_VAL, ERR_TEMP_VAL * 2)
    temp_sensor3 = feature_temperature(TARGET_TEMP_VAL, ERR_TEMP_VAL * 4)
    
    sensor1.add_feature(temp_sensor1)
    sensor2.add_feature(temp_sensor2)
    sensor3.add_feature(temp_sensor3)

    # Declare humidity feature
    humidity_sensor1 = feature_humidity(TARGET_HUMIDITY_VAL, ERR_HUMIDITY_VAL)
    humidity_sensor2 = feature_humidity(TARGET_HUMIDITY_VAL, ERR_HUMIDITY_VAL * 4)
    humidity_sensor3 = feature_humidity(TARGET_HUMIDITY_VAL, ERR_HUMIDITY_VAL * 8)

    sensor1.add_feature(humidity_sensor1)
    sensor2.add_feature(humidity_sensor2)
    sensor3.add_feature(humidity_sensor3)

    # Declare CO2 feature
    co2_sensor1 = feature_co2(TARGET_CO2_VAL, ERR_CO2_VAL)
    co2_sensor2 = feature_co2(TARGET_CO2_VAL, ERR_CO2_VAL * 2)
    co2_sensor3 = feature_co2(TARGET_CO2_VAL, ERR_CO2_VAL * 4)

    sensor1.add_feature(co2_sensor1)
    sensor2.add_feature(co2_sensor2)
    sensor3.add_feature(co2_sensor3)

    # Configure satisfaction evaluator
    temp_satisfaction_eval = satisfaction_temperature(TARGET_TEMP_VAL)
    humidity_satisfaction_eval = satisfaction_humidity(TARGET_HUMIDITY_VAL)
    co2_satisfaction_eval = satisfaction_co2(TARGET_CO2_VAL)

    # Configure feature weights
    feature_weights = {feature_type.TEMPERATURE: 0.33,
                       feature_type.HUMIDITY: 0.33,
                       feature_type.CO2: 0.33}

    # Create naive bayes reputation model
    nb = {}
    for sensor_item in sensors:
        nb[sensor_item.get_name()] = naive_bayes(sensor_item.get_name(), feature_weights, SATISFACTION_THRESHOLD)

        # Add satisfaction evaluator to NB model
        nb[sensor_item.get_name()].add_satisfaction(temp_satisfaction_eval)
        nb[sensor_item.get_name()].add_satisfaction(humidity_satisfaction_eval)
        nb[sensor_item.get_name()].add_satisfaction(co2_satisfaction_eval)

    # Run the first half of the simulation
    for i in range(0, SIMULATION_LOOP):
        for sensor_item in sensors:        
            # Generate sensor data        
            data = sensor_item.get_data()
            nb[sensor_item.get_name()].compute(data)
            nb[sensor_item.get_name()].save_reputation()

    # Sensor3 should deliver the best info. Sensor2 should deliver the second best info and Sensor1 should deliver the third best info.
    temp_sensor1.set_target_error(TARGET_TEMP_VAL, ERR_TEMP_VAL * 32)
    temp_sensor2.set_target_error(TARGET_TEMP_VAL, ERR_TEMP_VAL * 1.5)
    temp_sensor3.set_target_error(TARGET_TEMP_VAL, ERR_TEMP_VAL)

    humidity_sensor1.set_target_error(TARGET_HUMIDITY_VAL, ERR_HUMIDITY_VAL * 32)
    humidity_sensor2.set_target_error(TARGET_HUMIDITY_VAL, ERR_HUMIDITY_VAL * 2)
    humidity_sensor3.set_target_error(TARGET_HUMIDITY_VAL, ERR_HUMIDITY_VAL)

    co2_sensor1.set_target_error(TARGET_CO2_VAL, ERR_CO2_VAL * 32)
    co2_sensor2.set_target_error(TARGET_CO2_VAL, ERR_CO2_VAL * 1.5)
    co2_sensor3.set_target_error(TARGET_CO2_VAL, ERR_CO2_VAL)

    # Run the second half of the simulation (give it enough time to recover)
    for i in range(0, SIMULATION_LOOP * 10):
        for sensor_item in sensors:        
            # Generate sensor data        
            data = sensor_item.get_data()
            nb[sensor_item.get_name()].compute(data)
            nb[sensor_item.get_name()].save_reputation()

    # Plot the reputation probability
    legend = []
    for sensor_item in sensors:
        legend.append(sensor_item.get_name())
        plt.plot(nb[sensor_item.get_name()].get_reputation_history([feature_type.TEMPERATURE, feature_type.HUMIDITY, feature_type.CO2]))

    plt.xlabel("Steps")
    plt.ylabel("Trust reputation probability")
    plt.legend(legend)
    plt.show()
Beispiel #24
0
#!/usr/bin/env python
import time
import os
import RPi.GPIO as GPIO
from sensor import *

### creates a sensor object out of the first channel and displays the
### value on the screen as you turn the knob







mySensor = sensor(0,0,'knob')

while True:
	mySensor.update()
	### system volume requires an int 0..100
	set_volume = mySensor.getValue()/10.24
	set_volume = round(set_volume)
	set_volume = int(set_volume)
	
	###Operating system magic
	set_vol_cmd = 'sudo amixer cset numid=1 -- {volume}% > /dev/null' .format(volume = set_volume)
	os.system(set_vol_cmd)
	
Beispiel #25
0
	def __init__(self, adc, channel, sensitivity):
		self.sensor = sensor(adc, channel, "light")
		self.sensitivity = sensitivity
Beispiel #26
0
Datei: mixerf.py Projekt: emwg/pi
import sndobj
import time
from sensor import *
from lightSensor import *
from flexSensor import *

fsensor = flexSensor(2, 1)
lsensor = lightSensor(1, 10)
knob = sensor(0, 'knob')
knob.setTolerance(2)

tab = sndobj.HarmTable(1000, 50, 1)
osc1 = sndobj.Oscili(tab, 1, 0)
osc1amp = 0
#osc2 = sndobj.Oscili(tab, 1, 5000)
#osc3 = sndobj.Oscili(tab, 1, 5000)
#osc4 = sndobj.Oscili(tab, 1, 5000)
mod = sndobj.Oscili(tab, 1, 100)
out = sndobj.SndRTIO(1, sndobj.SND_OUTPUT)
#delay = sndobj.DelayLine(1, osc2)
mixer = sndobj.Mixer()

mod.SetFreq(0)
osc1.SetFreq(0, mod)
osc1freq = 0
#osc2.SetFreq(400, mod)
#osc3.SetFreq(300, mod)
#osc4.SetFreq(500, mod)
mixer.AddObj(osc1)
#mixer.AddObj(osc2)
#mixer.AddObj(osc3)