コード例 #1
0
class Printer:

    def __init__(self, connection, printer_name):
        self.connection = connection
        self.printer_name = printer_name
        self.power = Power()

    def printer(self):
        printers = self.connection.getPrinters()
        return printers[self.printer_name]

    def cancel_all_jobs(self):
        self.connection.cancelAllJobs(self.printer_name)

    @timeout(120)
    def send_file_to_printer(self, image):
        job_id = self.connection.printFile(self.printer_name, image.file_path, "", {})

    def send(self, image):
        SupportTeam.notify("%s - cancelling all jobs" % image.media.id)
        self.cancel_all_jobs()

        SupportTeam.notify("%s - turning printer off (5 secs)" % image.media.id)
        self.power.turn_off()
        time.sleep(5)

        SupportTeam.notify("%s - turning printer on (15 secs)" % image.media.id)
        self.power.turn_on()
        time.sleep(15)

        # it takes about a minute to print an image. 1.5 mins is conservative.
        SupportTeam.notify("%s - sent to printer, waiting to print (90 secs)" % image.media.id)
        self.send_file_to_printer(image)
        time.sleep(90)
コード例 #2
0
ファイル: gravis.py プロジェクト: bpittman/pydnd
 def __init__(self):
    Power.__init__(self)
    self.frequency = 'encounter'
    self.action = 'minor'
    self.maxUses = 2
    self.usesRemaining = 2
    self.keywords = ['divine','healing']
コード例 #3
0
ファイル: linder.py プロジェクト: bpittman/pydnd
 def __init__(self):
     Power.__init__(self)
     self.frequency = "at-will"
     primary = Attack()
     primary.attackType = "dex"
     primary.defenseType = "AC"
     primary.weaponsOfDamage = 1
     primary.abilityModDamage = ["dex", "cha"]
     self.setAttack(primary=primary)
コード例 #4
0
ファイル: linder.py プロジェクト: bpittman/pydnd
 def __init__(self):
     Power.__init__(self)
     primary = Attack()
     primary.attackType = "dex"
     primary.defenseType = "AC"  # FIXME: or ref
     primary.weaponsOfDamage = 2
     primary.abilityModDamage = ["dex"]
     self.frequency = "encounter"
     self.setAttack(primary=primary)
コード例 #5
0
ファイル: linder.py プロジェクト: bpittman/pydnd
 def __init__(self):
     Power.__init__(self)
     primary = Attack()
     primary.attackType = "dex"
     primary.defenseType = "ref"
     primary.weaponsOfDamage = 0
     self.frequency = "encounter"
     self.action = "minor"
     self.setAttack(primary=primary)
コード例 #6
0
ファイル: gravis.py プロジェクト: bpittman/pydnd
 def __init__(self):
    Power.__init__(self)
    self.frequency = 'encounter'
    self.keywords = ['divine','implement']
    primary = Attack()
    primary.attackType = 'wis'
    primary.defenseType = 'for'
    primary.weaponsOfDamage = 0
    self.setAttack(primary=primary)
コード例 #7
0
def test_threshold():
    power = Power(0, 0)
    params = {'a': 0.01, 'b': 0, 'c': 1}
    
    assert power._threshold(+1.0, params) == 1.0
    assert power._threshold(+0.0, params) == 1.0
    assert power._threshold(-1.0, params) == 1.01
    assert power._threshold(-10.0, params) == 2
    assert power._threshold(-20.0, params) == 5
コード例 #8
0
ファイル: linder.py プロジェクト: bpittman/pydnd
 def __init__(self):
     Power.__init__(self)
     primary = Attack()
     primary.attackType = "dex"
     primary.defenseType = "AC"
     primary.weaponsOfDamage = 3
     primary.abilityModDamage = ["dex"]
     self.frequency = "daily"
     self.setAttack(primary=primary)
コード例 #9
0
ファイル: gravis.py プロジェクト: bpittman/pydnd
 def __init__(self):
    Power.__init__(self)
    self.frequency = 'at-will'
    self.keywords = ['divine','healing','implement']
    primary = Attack()
    primary.attackType = 'wis'
    primary.defenseType = 'ref'
    primary.weaponsOfDamage = 0
    primary.extraAttack = 2
    self.setAttack(primary=primary)
コード例 #10
0
ファイル: gravis.py プロジェクト: bpittman/pydnd
 def __init__(self):
    Power.__init__(self)
    self.frequency = 'encounter'
    self.keywords = ['divine','radiant','weapon']
    primary = Attack()
    primary.attackType = 'str'
    primary.defenseType = 'AC'
    primary.weaponsOfDamage = 2
    primary.abilityModDamage = ['str','wis']
    self.setAttack(primary=primary)
コード例 #11
0
ファイル: gravis.py プロジェクト: bpittman/pydnd
 def __init__(self):
    Power.__init__(self)
    self.frequency = 'encounter'
    self.keywords = ['conjuration','divine','implement','radiant']
    primary = Attack()
    primary.attackType = 'wis'
    primary.defenseType = 'ref'
    primary.nonWeaponDamageDie = 'd8'
    primary.nonWeaponNumDie = 2
    primary.abilityModDamage = ['wis']
    self.setAttack(primary=primary)
コード例 #12
0
ファイル: gravis.py プロジェクト: bpittman/pydnd
 def __init__(self):
    Power.__init__(self)
    self.frequency = 'daily'
    primary = Attack()
    primary.attackType = 'wis'
    primary.defenseType = 'AC'
    primary.nonWeaponDamageDie = 'd10'
    primary.nonWeaponNumDie = 1
    primary.abilityModDamage = ['wis']
    self.setAttack(primary=primary)
    self.keywords = ['divine','implement','conjuration']
コード例 #13
0
ファイル: gravis.py プロジェクト: bpittman/pydnd
 def __init__(self):
    Power.__init__(self)
    self.frequency = 'at-will'
    self.keywords = ['divine','implement','radiant']
    primary = Attack()
    primary.attackType = 'wis'
    primary.defenseType = 'ref'
    primary.nonWeaponDamageDie = 'd6'
    primary.nonWeaponNumDie = 1
    primary.abilityModDamage = ['wis']
    self.setAttack(primary=primary)
コード例 #14
0
    def __init__(self):
        self.logger = logging.getLogger('hvac-pid')
        self.logger.info('Starting hvac-pid')

        self.config = Config()
        self.util = Util()

        # PID options
        pid_options = self.config.getPIDOptions(self.mode)
        temp_options = self.config.getTempOptions(self.mode)

        # Temp
        self.temp = Temp(**{**temp_options, **pid_options})

        # Fan
        self.fan = Fan()

        # Power
        self.power = Power()

        # Occupancy state
        self.state = State(**self.config.getStateOptions())

        # MQTT
        self.topic_prefix = os.getenv('MQTT_PID_TOPIC_PREFIX')
        self.mqtt = MQTTClient(os.getenv('MQTT_CLIENT_ID'),
                               os.getenv('MQTT_BROKER_HOST'))
        self.mqtt.connect()

        # subscribe
        self.mqtt.subscribe(os.getenv('MQTT_TEMP_TOPIC'), 0,
                            self.temp_update_callback)
        self.mqtt.subscribe(os.getenv('MQTT_TEMP_OUTDOORS_TOPIC'), 0,
                            self.temp_outdoors_update_callback)
        self.mqtt.subscribe(os.getenv('MQTT_HVAC_STATE_TOPIC'), 0,
                            self.hvac_callback)
        self.mqtt.subscribe(self.topic_prefix + '/mode/set', 0, self.set_mode)
        self.mqtt.subscribe(self.topic_prefix + '/temperature/set', 0,
                            self.set_temp)
        self.mqtt.subscribe(self.topic_prefix + '/fan/set', 0, self.set_fan)
        self.mqtt.subscribe(os.getenv('MQTT_HVAC_OCCUPANCY_STATE_TOPIC'), 0,
                            self.set_occupancy_state)

        self.logger.info('MQTT connected')

        self.publish_temp()
        self.publish_mode()
        self.publish_fan()

        self.next_iteration = datetime.now() + timedelta(minutes=2)

        # wait a bit before enabling control
        time.sleep(5)
        self.control_enable = True
コード例 #15
0
ファイル: linder.py プロジェクト: bpittman/pydnd
 def __init__(self):
     Power.__init__(self)
     self.frequency = "daily"
     targetBloodied = Attack()
     targetBloodied.attackType = "dex"
     targetBloodied.defenseType = "AC"
     targetBloodied.weaponsOfDamage = 5
     targetBloodied.abilityModDamage = ["dex", "str"]
     targetUnbloodied = Attack()
     targetUnbloodied.attackType = "dex"
     targetUnbloodied.defenseType = "AC"
     targetUnbloodied.weaponsOfDamage = 3
     targetUnbloodied.abilityModDamage = ["dex"]
     self.setAttack(targetBloodied=targetBloodied, targetUnbloodied=targetUnbloodied)
コード例 #16
0
ファイル: main.py プロジェクト: shannon-jia/oled
 def __init__(self,
              arrmenu=[
                  "Menu:",
                  "Ipconfig",
                  "Set Date",
                  "Set Mask",
                  "set GateWay",
              ]):
     self.power = Power()
     self.screen = Screen()
     self.info = self.screen.get_info()
     self.keyboard = KeyBoard(5, 6, 26, 22)
     self.strmenu = arrmenu
     self.menu_index = 0
     self.state = 'FIRSTPAGE'
     self.list_gateway = []
     self.marker = 0
     self.list_mask = []
     self.list_addr = []
     self.x = []
     self.list_date = self.info[1]
     self.marker = 0
     self.cmd1 = ''
     self.cmd2 = ''
     self.cmd3 = ''
     self.cmd4 = ''
     self.cmd5 = ''
コード例 #17
0
def start_game(timer):

    mango = Fruit("mango", 15, "mango.png", .2)
    forbiddenMango = Fruit("forbidden mango", -15, "mango.png", .7)
    apple = Fruit("apple",10,"apple.png",.5)
    badApple = Fruit("bad apple",-10,"badapple.png",.5)
    orange = Fruit("orange", 5, "orange.png", .7)
    pineapple = Fruit("pinapple", 15, "pinapple.png", .4)
    fruits = [mango, forbiddenMango, apple, badApple, orange, pineapple]

    power = Power("Faster Basket","Faster Basket",0,"power1.png",.9,5)
    power2 = Power("10 Extra Points", "10 Extra Points", 10,"power2.png", .9,0)

    powers = [power, power2]
    poisons = [Poison.send_poison(), Poison.slower(), Poison.burn()]

    seconds = timer
    start = time.time()
    time.process_time()
    elapsed = 0
    power_random = random.randint(0,seconds)

    print("Get Ready!")
    print(f"You have {seconds} seconds to catch as many fruits as you can!")
    while elapsed <= seconds:
        print(f"Total score: {basket.get_score()}")
        elapsed = time.time() - start
        fruit = random.choice(fruits)
        pw = random.choice(powers)
        poison = random.choice(poisons)
        slowed, poison_score, message = poison
        basket.catch_fruit(fruit.get_score())
        if int(elapsed) == power_random:
            basket.catch_fruit(pw.get_score())
            style = add_style(pw.announce)
            print(style())
            basket.use_power(pw.get_time(), pw.get_ability(), pw.get_score())
        if int(elapsed) == 3:
            print(message)
            basket.catch_fruit(poison_score)
            basket.set_speed(slowed)
        print(f"Catched: {fruit.announce()}") 
        time.sleep(1)
    
    basket.update_highsore()

    print(f"Game Over\nScore: {basket.get_score()} | Highscore: {basket.get_highscore()}")
コード例 #18
0
 def test_create_power_with_args(self):
     args = {
         'name': 'charge',
         'rule': 'Can move at half speed (rnd up) and then attack!',
         'colour': 'green'
     }
     new_power = Power(**args)
     self.assertIsNotNone(new_power)
コード例 #19
0
ファイル: main.py プロジェクト: SpecialWater/Aquatron
    def __init__(self):
        # self.URL = "http://192.168.179.227:5001"
        self.URL = "https://pruetpiflask.azurewebsites.net"
        self.token = self.login()
        self.temp_sensor = Temperature()
        self.outlets = Power()
        self.tz = pytz.timezone('US/Central')

        # default state
        self.state = {
            "Temperature": 0,
            "pH": 0,
            "Light_UV_On": True,
            "Light_Refugium_On": True,
            "GasInjection_On": True,
            "Heater_On": True,
            "Pump_Power": 3
        }

        asyncio.run(self.main())
コード例 #20
0
ファイル: track.py プロジェクト: wx4cb/boresight
    def __init__(self, config):
        self.servo_power = Power(config)
        self.servo_power.set_relay_two_off()

        self.degrees_per_radian = 180.0 / math.pi
        self.home = ephem.Observer()
        self.home.lon = config['home']['lng']
        self.home.lat = config['home']['lat']
        self.home.elevation = float(config['home']['alt'])

        self.elements = []

        self.lsm = LSM303DLHC()
        self.lsm.set_declination(10, 40)
        self.servo = Servo(config, self.lsm)

        self.log = logging.getLogger('boresight')
        self._running = True
        self._worker = threading.Thread(target=self._track_worker)
        self._worker.setDaemon(True)
        self._worker.start()
コード例 #21
0
class Printer:
    def __init__(self, connection, printer_name):
        self.connection = connection
        self.printer_name = printer_name
        self.power = Power()

    def printer(self):
        printers = self.connection.getPrinters()
        return printers[self.printer_name]

    def cancel_all_jobs(self):
        self.connection.cancelAllJobs(self.printer_name)

    @timeout(120)
    def send_file_to_printer(self, image):
        job_id = self.connection.printFile(self.printer_name, image.file_path,
                                           "", {})

    def send(self, image):
        SupportTeam.notify("%s - cancelling all jobs" % image.media.id)
        self.cancel_all_jobs()

        SupportTeam.notify("%s - turning printer off (5 secs)" %
                           image.media.id)
        self.power.turn_off()
        time.sleep(5)

        SupportTeam.notify("%s - turning printer on (15 secs)" %
                           image.media.id)
        self.power.turn_on()
        time.sleep(15)

        # it takes about a minute to print an image. 1.5 mins is conservative.
        SupportTeam.notify("%s - sent to printer, waiting to print (90 secs)" %
                           image.media.id)
        self.send_file_to_printer(image)
        time.sleep(90)
コード例 #22
0
def get_power_board():
    devs = _list_usb_devices('Power_board_v4')

    srdev = None
    for dev in devs:
        serialnum = dev["ID_SERIAL_SHORT"]

        if "BUSNUM" in dev:
            srdev = Power(dev.device_node,
                          busnum=int(dev["BUSNUM"]),
                          devnum=int(dev["DEVNUM"]),
                          serialnum=serialnum)
            break

    return srdev
コード例 #23
0
def main():
	from power import Power

	p = Power("/dev/ttyACM0", debug=False)
	p.print_conf()

	vcc = p.get_vcc()
	print "Vcc={}".format(vcc)

	a = PowerAnalyzer(p)

	#a.run(record_path="analyzer.avi", frames=40)
	a.run()

	p.close()
コード例 #24
0
ファイル: track.py プロジェクト: zhkj2010/boresight
    def __init__(self, config):
        self.servo_power = Power(config)
        self.servo_power.set_relay_two_off()

        self.degrees_per_radian = 180.0 / math.pi
        self.home = ephem.Observer()
        self.home.lon = config['home']['lng']
        self.home.lat = config['home']['lat']
        self.home.elevation = float(config['home']['alt'])

        self.elements = []

        self.lsm = LSM303DLHC()
        self.lsm.set_declination(10, 40)
        self.servo = Servo(config, self.lsm)

        self.log = logging.getLogger('boresight')
        self._running = True
        self._worker = threading.Thread(target=self._track_worker)
        self._worker.setDaemon(True)
        self._worker.start()
コード例 #25
0
 def test_create_power(self):
     with self.assertRaises(InvalidPowerArgs):
         new_power = Power()
コード例 #26
0
def test_cooling_power_off():
    state = False
    request = 21.0
    threshold = 1.0
    hysteresis = 0.5

    power = Power(threshold, hysteresis)

    #  below request, below threshold, below hysteresis => power off
    power.state = state
    power.calculate(request, request - threshold - hysteresis - 1, 'cool')
    assert power.state == False

    #  below request, below threshold, above hysteresis => power off
    power.state = state
    power.calculate(request, request - threshold - (hysteresis / 2), 'cool')
    assert power.state == False

    #  below request, above threshold => power on
    power.state = state
    power.calculate(request, request - (threshold / 2), 'cool')
    assert power.state == True
コード例 #27
0
ファイル: driver.py プロジェクト: slugwarz05/proj2-code
    def drive(self,
              max_iterations=500,
              random_seed=0,
              initial_pop=50):
        """
        Args:
            max_iterations: Integer. The maximum number of iterations the
                simulation should run.
            random_seed: Integer. Seed for the random number generator.
            initial_pop: Integer. The initial population for the population.

        Returns:
            None.
        """

        # Dictionary to keep track of results
        self.results = defaultdict(list)

        # Seed the random number generator.
        random.seed(random_seed)

        # Create a dictionary that will hold the number of newborns that will
        # be added to the simulation.
        people_born = { k: 0 for k in range(9) }

        # Set the maximum number of iterations that the simulation will run.
        max_sim_time = max_iterations

        # Initialize a population.
        population = Population()

        # Initialize an air instance for modeling oxygen consumption.
        air = Air(population)

        # Initialize a power instance for modeling power consumption.
        power = Power(population)

        # Initial Iteration
        cur_sim_time = 0
        start = time.time()

        # Add initial population
        initial_ages = [10, 18, 20, 25, 28, 30, 32, 35, 40, 45, 50, 55]
        for add_count in range (initial_pop):
            init_age = cur_sim_time - initial_ages[add_count % len(initial_ages)]*12.0
            population.add_person(Person(init_age, population.get_rand_death_time(cur_sim_time), random.random()))
        print 'added', people_born.get(cur_sim_time % 9, 0), 'people in', time.time()-start

        start = time.time()
        total_kcal = population.kcal_requirements(cur_sim_time)
        print 'completed total kcal in:', time.time() - start

        # Create a facility for population
        # Crop area of 25000 feeds about 30 people
        facility = Facility(30000.0/30.0*(initial_pop+30), initial_pop+30)

        # Food initialization
        food = Food(facility, total_kcal)

        # Create a disaster object for the population - this models uncertainty
        # events that may adversely affect the population & food
        disaster = Disaster(population, food)

        # Write initial loop results
        self._write_results(population=population.num_people(),
                            food=food.produced_food,
                            kcals=total_kcal,
                            facility_crop=facility.crop_area,
                            facility_personnel=facility.personnel_capacity,
                            air=air.oxygen_consumed(),
                            power=power.power_consumed())

        # Main iteration loop
        for cur_sim_time in range(1, max_sim_time):
            print 'current sim time:', cur_sim_time
            start = time.time()

            # Diasters
            if random.random() <= 0.01:
                #ratio = random.random()/10.0
                #disaster.create_disaster(ratio)
                #print 'DISASTER killed', ratio, 'in:', time.time() - start
                death_from_disaster = random.randint(1,20)
                disaster.create_disaster(death_from_disaster)
                print 'DISASTER killed', death_from_disaster, 'people and', (death_from_disaster+10)*2500.0, 'food in:', time.time() - start
                start = time.time()

            # If enough food, expand facility. Assume 3 month build time
            if food.remaining_food > 2500*10 and (facility.personnel_capacity - population.num_people()) <= 10:
                facility.start_pod_construction(cur_sim_time, 3)
                facility.add_pod(cur_sim_time)

            # Adding newborns
            born_count = 0
            for add_count in range (people_born.get(cur_sim_time % 9, 0)):
                if population.num_people() < facility.personnel_capacity:
                    population.add_person(Person(cur_sim_time, population.get_rand_death_time(cur_sim_time), random.random()))
                    born_count += 1
            print 'added', born_count, 'people in', time.time()-start

            # Removing the dead
            start = time.time()
            people_to_kill = len(population.death_dict.get(cur_sim_time, []))
            population.remove_dead(cur_sim_time)
            print 'removed', people_to_kill, 'people in:', time.time() - start

            # Calculating total kcal
            start = time.time()
            total_kcal = population.kcal_requirements(cur_sim_time)
            print 'completed total kcal in:', time.time() - start

            # Food consumption
            food_delta = food.update_food(total_kcal)
            print 'produced food = ', food.produced_food, '; remaining food = ', food.remaining_food
            # if not enough food
            if food_delta < 0:
                # people who are unfed will die, starting with oldest people
                while (food_delta < 0):
                    food_delta = food_delta + population.people[0].kcal_requirements(cur_sim_time)
                    population.remove_person(0)
                population.generate_death_dict()

            # Calculating how many newborns to be created in 9 months time
            num_people = population.num_people()
            num_adults = population.num_adults(cur_sim_time)
            # newborns based on number of adults. Average US birthrate in 2014: 0.01342 (indexmundi.com)
            people_born[cur_sim_time % 9] = random.randint(np.rint(num_adults*0.01),np.rint(num_adults*0.020))
            print 'total people:', num_people, 'and total adults:', num_adults, 'and total kcal:', total_kcal
            print 'total capacity:', facility.personnel_capacity

            print('-'*100)

            # Record results of the iteration.
            self._write_results(population=num_people,
                                food=food.produced_food,
                                kcals=total_kcal,
                                facility_crop=facility.crop_area,
                                facility_personnel=facility.personnel_capacity,
                                air=air.oxygen_consumed(),
                                power=power.power_consumed())

            # If the visualization option has been selected, plot the results
            # every 10 timesteps.
            if self.vis and cur_sim_time % 10 == 0:

                # Add data for the chart.
                self.vis.add_data(cur_sim_time, {
                    'Population Count': num_people,
                    'Adult Count': num_adults,
                    'Caloric Requirements (Mcal)': total_kcal / 1000.0,
                    'Produced Food (Mcal)': food.produced_food / 1000.0,
                    'Air (kg O2)': air.oxygen_consumed(),
                    'Power Consumption (kWh)': power.power_consumed()
                })

                # Update the chart, re-rendering.
                self.vis.update()

        # If visualization has been selected,
        if self.vis:
            # Save the last rendered chart as a png image.
            self.vis.savefig()

        # Return the results dict.
        return self.results
コード例 #28
0
 def __init__(self, connection, printer_name):
     self.connection = connection
     self.printer_name = printer_name
     self.power = Power()
コード例 #29
0
def test_heating_power_off():
    state = False
    request = 21.0
    threshold = 1.0
    hysteresis = 0.5

    power = Power(threshold, hysteresis)

    #  above request, above threshold, above hysteresis => power off
    power.state = state
    power.calculate(request, request + threshold + hysteresis + 1, 'heat')
    assert power.state == False

    #  above request, above threshold, below hysteresis => power off
    power.state = state
    power.calculate(request, request + threshold + (hysteresis / 2), 'heat')
    assert power.state == False

    #  above request, below threshold => power on
    power.state = state
    power.calculate(request, request + (threshold / 2), 'heat')
    assert power.state == True
コード例 #30
0
class HVACPIDController(object):
    logger = None
    mqtt = None
    temp = None
    fan = None
    power = None
    config = None
    state = None

    temp_outdoors = 0

    mode = 'auto'
    manual = False
    control_enable = False
    hvac_state = {}
    next_iteration = None

    def __init__(self):
        self.logger = logging.getLogger('hvac-pid')
        self.logger.info('Starting hvac-pid')

        self.config = Config()
        self.util = Util()

        # PID options
        pid_options = self.config.getPIDOptions(self.mode)
        temp_options = self.config.getTempOptions(self.mode)

        # Temp
        self.temp = Temp(**{**temp_options, **pid_options})

        # Fan
        self.fan = Fan()

        # Power
        self.power = Power()

        # Occupancy state
        self.state = State(**self.config.getStateOptions())

        # MQTT
        self.topic_prefix = os.getenv('MQTT_PID_TOPIC_PREFIX')
        self.mqtt = MQTTClient(os.getenv('MQTT_CLIENT_ID'),
                               os.getenv('MQTT_BROKER_HOST'))
        self.mqtt.connect()

        # subscribe
        self.mqtt.subscribe(os.getenv('MQTT_TEMP_TOPIC'), 0,
                            self.temp_update_callback)
        self.mqtt.subscribe(os.getenv('MQTT_TEMP_OUTDOORS_TOPIC'), 0,
                            self.temp_outdoors_update_callback)
        self.mqtt.subscribe(os.getenv('MQTT_HVAC_STATE_TOPIC'), 0,
                            self.hvac_callback)
        self.mqtt.subscribe(self.topic_prefix + '/mode/set', 0, self.set_mode)
        self.mqtt.subscribe(self.topic_prefix + '/temperature/set', 0,
                            self.set_temp)
        self.mqtt.subscribe(self.topic_prefix + '/fan/set', 0, self.set_fan)
        self.mqtt.subscribe(os.getenv('MQTT_HVAC_OCCUPANCY_STATE_TOPIC'), 0,
                            self.set_occupancy_state)

        self.logger.info('MQTT connected')

        self.publish_temp()
        self.publish_mode()
        self.publish_fan()

        self.next_iteration = datetime.now() + timedelta(minutes=2)

        # wait a bit before enabling control
        time.sleep(5)
        self.control_enable = True

    def iterate(self):
        if self.manual:
            self.logger.info('Manual mode, skipping PID iteration')
        else:
            compensated_request_temp = self.state.compensateRequestTemp(
                self.temp.temp_request, self.temp_outdoors)
            max_set_temp = ceil(self.temp.temp_absolute) + 3

            # temp hax
            # limit min temp when outdoors is < -10
            if self.temp_outdoors < -10:
                self.temp.setLimits(
                    floor(compensated_request_temp) - 1, max_set_temp)
                self.logger.debug(
                    'Limiting min temp to %g when outdoor temp is %g',
                    self.temp.temp_min, self.temp_outdoors)
            else:
                self.temp.setLimits(self.config.getSetTempMin(), max_set_temp)

            self.temp.iteratePID(compensated_request_temp)
            self.fan.calculate(self.temp.pid_offset, self.mode)
            self.power.calculate(self.temp.temp_request,
                                 self.temp.temp_measure, self.mode,
                                 self.temp_outdoors)
            if not self.power.state:
                self.temp.reset()
            self.publish_state()

    def temp_update_callback(self, client, userdata, message):
        payload_json = json.loads(message.payload.decode('utf-8'))

        if 'temperature' in payload_json:
            temp = payload_json['temperature']
        else:
            temp = payload_json['tempc']

        if 'humidity' in payload_json:
            humidity = payload_json['humidity']
        else:
            humidity = payload_json['hum']

        if self.mode == 'cool':
            dew_point = self.util.dewPoint(temp, humidity)
            self.temp.setMeasurement(round(dew_point, 2), temp)
        else:
            self.temp.setMeasurement(temp, temp)

    def temp_outdoors_update_callback(self, client, userdata, message):
        payload_json = json.loads(message.payload.decode('utf-8'))
        self.temp_outdoors = float(payload_json['temperature'])

    def hvac_callback(self, client, userdata, message):
        payload_json = json.loads(message.payload.decode('utf-8'))
        self.logger.info('Received hvac state change %s', payload_json)
        self.hvac_state = payload_json

    def setHVAC(self):
        if self.control_enable:
            topic = os.getenv('MQTT_HVAC_TOPIC')
            new_state = {
                'power': self.power.state,
                'mode': self.mode.upper(),
                'temperature': self.temp.temp_set,
                'fan': self.fan.speed,
            }

            is_state_changed = (new_state['power']
                                and self.hvac_state != new_state)
            is_power_state_changed = (
                self.hvac_state
                and new_state['power'] != self.hvac_state['power'])
            old_state_doesnt_exists = (not self.hvac_state)

            if is_state_changed or is_power_state_changed or old_state_doesnt_exists:
                message = json.dumps(new_state)

                self.logger.debug('Controlling HVAC with command %s', message)
                self.mqtt.publish(topic, message, 1)
            else:
                self.logger.debug('HVAC state unchanged %s', self.hvac_state)
        else:
            self.logger.debug('Controlling HVAC disabled')

    def set_mode(self, client, userdata, message):
        mode = message.payload.decode('utf-8')
        previous_mode = self.mode

        # reset PID if switching between modes
        if previous_mode != mode:
            pid_options = self.config.getPIDOptions(mode)
            temp_options = self.config.getTempOptions(mode)
            self.temp = Temp(**{**temp_options, **pid_options})

        if mode == 'off':
            self.manual = True
            self.mode = 'auto'
            self.power.state = False
            self.logger.info('Set mode to off')
        if mode == 'auto':
            self.manual = True
            self.power.state = True
            self.mode = 'auto'
            self.temp.temp_set = self.temp.temp_request
            self.logger.info('Set mode to manual')
        elif mode == 'heat':
            self.manual = False
            self.mode = mode
            self.logger.info('Set mode to %s', self.mode)
        elif mode == 'cool':
            self.manual = False
            self.mode = mode
            self.temp.temp_set = self.temp.temp_absolute
            self.logger.info('Set mode to %s', self.mode)

        self.state.setMode(mode)
        self.publish_mode()
        self.setHVAC()
        self.set_next_iteration(2)

    def publish_mode(self):
        if not self.control_enable:
            return

        topic = self.topic_prefix + '/mode/state'

        if self.manual:
            if self.power.state == False:
                mode = 'off'
            else:
                mode = 'manual'
        elif self.mode == 'auto':
            mode = 'manual'
        else:
            mode = self.mode

        self.mqtt.publish(topic, mode, 1, True)

    def set_temp(self, client, userdata, message):
        temp = round(float(message.payload.decode('utf-8')), 2)

        if temp >= float(os.getenv('REQUEST_MIN_TEMP', 0)) and temp <= float(
                os.getenv('REQUEST_MAX_TEMP', 100)):
            self.temp.setRequest(temp)

            if self.manual:
                self.temp.temp_set = self.temp.temp_request
            else:
                self.temp.reset()

            self.publish_temp()
            self.setHVAC()

    def publish_temp(self):
        if not self.control_enable:
            return

        self.mqtt.publish(self.topic_prefix + '/temperature/state',
                          self.temp.temp_request, 1, True)
        self.mqtt.publish(self.topic_prefix + '/measured_temperature',
                          self.temp.temp_measure, 1, True)

    def set_fan(self, client, userdata, message):
        fan = message.payload.decode('utf-8')

        if fan != "auto":
            fan_int = int(fan)

            if self.manual and fan_int >= 0 and fan_int <= 5:
                self.fan.speed = fan_int
                self.publish_fan()
                self.setHVAC()
                self.logger.info('Manually set fan speed to %s/5',
                                 self.fan.speed)

    def publish_fan(self):
        if not self.control_enable:
            return

        topic = self.topic_prefix + '/fan/state'

        if self.manual:
            fan = self.fan.speed
        else:
            fan = 'auto'

        self.mqtt.publish(topic, fan, 1, True)

    def publish_state(self):
        if not self.control_enable:
            return

        topic = os.getenv('MQTT_PID_TOPIC_PREFIX') + '/state'
        message = json.dumps({
            'mode':
            self.mode,
            'manual':
            self.manual,
            'temperature_request':
            float(self.temp.temp_request),
            'temperature_set':
            float(self.temp.temp_set),
            'temperature_measure':
            float(self.temp.temp_measure),
            'temperature_error':
            float(self.temp.pid.previous_error),
            'set_temperature_lower_limit':
            float(self.temp.temp_min),
            'set_temperature_upper_limit':
            float(self.temp.temp_max),
            'fan':
            int(self.fan.speed if self.power.state else 0),
            'power':
            self.power.state,
            'Kp':
            float(self.temp.pid.Kp),
            'Ki':
            float(self.temp.pid.Ki),
            'Kd':
            float(self.temp.pid.Kd),
            'integral':
            float(self.temp.pid.integral),
            'integral_max':
            float(self.temp.pid.integral_max),
            'pid_offset':
            float(self.temp.pid_offset),
            'pid_result':
            float(self.temp.pid_result),
        })
        self.mqtt.publish(topic, message, 1)

    def set_occupancy_state(self, client, userdata, message):
        state = message.payload.decode('utf-8')
        prev_state = self.state.state
        self.state.setState(state)
        self.logger.info('Setting occupancy state to %s', self.state.state)

        # only reset if going or returning away state
        if prev_state == 'away' or self.state.state == 'away':
            self.temp.reset()
            self.set_next_iteration(2)

    def set_next_iteration(self, interval):
        self.next_iteration = datetime.now() + timedelta(minutes=interval)
        self.logger.info('Next iteration at %s', self.next_iteration)
コード例 #31
0
ファイル: gravis.py プロジェクト: bpittman/pydnd
 def __init__(self):
    Power.__init__(self)
    self.frequency = 'encounter'
    self.keywords = ['divine']
コード例 #32
0
all_beams = beams(board_obj)
all_beams.place()

magnets = magnet(board_obj)
magnets.place()

power = power_up(board_obj)
power.place()

hero = mandalorian()
hero.paste_mand(board_obj)

villain = boss_create()
villain.boss_update(board_obj)

dum3 = Power()

while 1:
    print("\033[0;0H", end="")
    dum3.Power_fn(board_obj, hero)
    dum3.check1(hero, board_obj)
    sh2 = dum3.retact()
    dum = coin1()
    dum2 = beam1()
    sh = mandamove(hero, board_obj, dum, dum2, villain)

    attraction(magnets, hero, board_obj, sh, dum, dum2)

    hero.update_mand(board_obj, sh2, sh, dum, dum2)
    if hero.ret__activ() == 1:
        hero.check(board_obj, dum2, villain)
コード例 #33
0
    choice = int(input("Choice please :-->  "))

    if(choice == 1):
        result = Addition.add(num1, num2)

    elif(choice == 2):
        result = Multiplication.multiply(num1, num2)

    elif(choice == 3):
        result = Division.division(num1, num2)

    elif(choice == 4):



        result = Power.power(num1, num2)

    elif(choice == 5):
        break



        result = IntegerDivision.integerdivision(num1,num2)


        result = Subtraction.subtraction(num1,num2)   
    
    elif(choice == 5):
        

        result = Modulo.mod(num1, num2)
コード例 #34
0
 def __init__(self, connection, printer_name):
     self.connection = connection
     self.printer_name = printer_name
     self.power = Power()
コード例 #35
0
ファイル: teddy.py プロジェクト: vschwartz-tgm/Kuscheltier
    def __init__(self, device=None, task=None, debug=False):
        self.debug = debug
        if self.debug:
            print("### Teddy mit debug output ....")
        self.task = task
        self.repeat = 0
        #
        # init pygame for sound
        #
        # good sound parameters for raspi
        # maybe get later from config file or database
        #
        frequency = 48000
        size = -16
        channels = 1
        buffer = 1024
        speed = 100
        voice = 'de'
        #
        if pygame.mixer.get_init() is None:
            pygame.mixer.init(frequency, size, channels, buffer)
        #
        signal.signal(signal.SIGINT, signal_handler)
        #
        # init button device
        #
        if device is None:
            self.dev = getDevice(self.debug)
        else:
            self.dev = device
        #
        # initializing external classes
        #
        self.simon = SimonSagt()
        self.buecher = BuecherLesen()
        self.termine = Termin()
        self.power = Power()

        # call checkPower every 10 seconds, forever
        pt = IntervalPower(10.0, self.power.checkPower)
        pt.start()
        # call checkTermin every 30 seconds, forever
        rt = IntervalTermin(30.0, self.termine.checkTermin)
        rt.start()

        #
        # Choose a language
        #

        #pygame.display.set_mode((200, 100))

        #pygame.mixer.music.load('D:\Diplomarbeit\Github\Kuscheltier\Teddy\Einleitung_Hallo2.wav')
        #pygame.mixer.music.load("teddy_audio/Einleitung/Einleitung_Hallo.wav")
        #pygame.mixer.music.play(0)

        #clock = pygame.time.Clock()
        #clock.tick(10)

        #pygame.mixer.music.play(1, 0)

        coutput(
            "Choose your language, press the right arm for german and the left arm for english"
        )
        pressed = getButton(self.dev, 10, self.debug)
        if pressed == RECHTER_ARM:
            teddy_language = "de"
        elif pressed == LINKER_ARM:
            teddy_language = "en"
        #
        # start task directly is defined for debugging ...
        #
        if self.task == "simon":
            self.simon.runSpiel(self.dev, self.debug)
        elif self.task == "buecher":
            self.buecher.runLesen(self.dev, self.debug)
        else:
            self.betterAsk(self.debug)
コード例 #36
0
ファイル: main.py プロジェクト: shannon-jia/oled
            z = "%02d:%02d" % (date[3], date[4])
            datetime = y + ' ' + z
            setcursor = [0, 1, 3, 4, 6, 7, 9, 10, 12, 13]
            self.marker = setcursor[self.marker]
            setmenu.append(datetime)
            self.screen.display(setmenu, self.marker, 3)
            self.cmd1 = "sudo date -s %s" % y
            self.cmd2 = "sudo date -s %s" % z
        else:
            pass


if __name__ == "__main__":
    screen = Screen()
    keyboard = KeyBoard()
    power = Power()
    main = Main([
        "Ipconfig", "Set Date", "Set Mask", "set GateWay", "Save", "Save",
        "Save", "Save", "Save", "Save"
    ])
    info = screen.get_info()
    screen.display(info)
    ip_underline = 0
    try:
        while True:
            r = power.is_reset_still_down()
            if r is True:
                cmd6 = "sudo shutdown -h now"
                main.inip_os(cmd6)
            else:
                pass
コード例 #37
0
            except Exception as inst:
                self.log.warn("_servo_worker thread exception")
                print type(inst)    # the exception instance
                print inst.args     # arguments stored in .args
                print inst          # __str__ allows args to be printed directly

        self.log.debug("sending thread exit")

if __name__ == '__main__':

    from time import sleep
    from lsm303dlhc import LSM303DLHC
    from power import Power

    config = {}

    lsm = LSM303DLHC()
    lsm.set_declination(10, 40)

    servo_power = Power(config)
    servo_power.set_relay_two_on()

    servo = Servo(config, lsm)
    servo.resume_tracking()
    servo.set_azimuth(340)
    servo.set_elevation(0)

    while True:
        sleep(1) # Output is fun to watch if this is commented out
コード例 #38
0
ファイル: track.py プロジェクト: zhkj2010/boresight
class Track:
    def __init__(self, config):
        self.servo_power = Power(config)
        self.servo_power.set_relay_two_off()

        self.degrees_per_radian = 180.0 / math.pi
        self.home = ephem.Observer()
        self.home.lon = config['home']['lng']
        self.home.lat = config['home']['lat']
        self.home.elevation = float(config['home']['alt'])

        self.elements = []

        self.lsm = LSM303DLHC()
        self.lsm.set_declination(10, 40)
        self.servo = Servo(config, self.lsm)

        self.log = logging.getLogger('boresight')
        self._running = True
        self._worker = threading.Thread(target=self._track_worker)
        self._worker.setDaemon(True)
        self._worker.start()

    def exit(self):
        self._running = False
        self.servo.exit()
        self.servo_power.cleanup()

    def set_elements(self, new_elements):
        self.elements = new_elements
        self.log.info("Elements updated.")


    def set_location(self, latitude, longitude, altitude):
        self.home.lon = str(longitude)
        self.home.lat = str(latitude)
        self.home.elevation = altitude

    def get_visible_satellite(self):
        first_sat = Satellite()
        first_element = True
        for index, element in enumerate(self.elements):
            self.home.date = datetime.utcnow()
            sat = ephem.readtle(element[0], element[1], element[2])
            sat.compute(self.home)
            rise_time, rise_azimuth, max_alt_time, max_alt, set_time, set_azimuth = self.home.next_pass(sat)
            name = element[0]
            element_index = index

            if (first_element == True or rise_time.datetime() <= first_sat.rise_time.datetime()):
                first_element = False
                first_sat = Satellite(element_index, rise_time, rise_azimuth, max_alt_time, max_alt, set_time, set_azimuth, name)
                self.log.info("Found Satellite: %s Rise time: %s azimuth: %s" % (first_sat.name, first_sat.rise_time, first_sat.rise_azimuth))

            self.log.info("Satellite: %s Rise time: %s azimuth: %s" % (name, rise_time, rise_azimuth))
        return first_sat

    def _track_worker(self):
        """
        Runs as a thread
        """
        sleep_interval = 2.0
        get_sat_interval = 120.0
        get_sat_next = time.time()
        satellite = Satellite()

        self.servo.pause_tracking()
        self.servo_power.set_relay_two_on()
        self.servo.park_servos()
        self.servo_power.set_relay_two_off()

        while self._running:
            try:
                if (len(self.elements) > 0):
                    self.log.info('%s: Rise: %s, Azimuth: %s' % (satellite.name, satellite.rise_time, satellite.rise_azimuth))
                    if (satellite.rise_time is not None and datetime.utcnow() > satellite.rise_time.datetime() and datetime.utcnow() < satellite.set_time.datetime()):

                        sleep_interval = 0.5
                        self.servo.resume_tracking()
                        self.servo_power.set_relay_two_on()

                        element = self.elements[satellite.element_index]
                        if (len(element) == 3):
                            sat = ephem.readtle(element[0], element[1], element[2])
                            # iss = ephem.readtle('ISS',
                            # '1 25544U 98067A   15002.52246161  .00016717  00000-0  10270-3 0  9002',
                            # '2 25544  51.6406 190.8516 0006769 204.9577 155.1248 15.52925311  2266'
                            # )
                            self.home.date = datetime.utcnow()
                            sat.compute(self.home)
                            altitude = sat.alt * self.degrees_per_radian
                            azimuth = sat.az * self.degrees_per_radian

                            self.servo.set_high_accuracy(False)
                            self.servo.set_azimuth(azimuth)
                            self.servo.set_elevation(altitude)
                            self.log.info('%s: altitude % 4.1f deg, azimuth % 5.1f deg' % (element[0], altitude, azimuth))
                    else:
                        sleep_interval = 5.0
                        self.servo.pause_tracking()
                        self.servo.park_servos()
                        self.servo_power.set_relay_two_off()
                        if (time.time() > get_sat_next):
                            get_sat_next = time.time() + get_sat_interval
                            satellite = self.get_visible_satellite()
                            azimuth = satellite.rise_azimuth * self.degrees_per_radian
                            self.servo.set_high_accuracy(False)

            except Exception as inst:
                print type(inst)    # the exception instance
                print inst.args     # arguments stored in .args
                print inst          # __str__ allows args to be printed directly
            time.sleep(sleep_interval)

            # except:
            #    self.log.warn("_track_worker thread exception")
            #    sleep(1)
        self.log.debug("sending thread exit")
コード例 #39
0
ファイル: linder.py プロジェクト: bpittman/pydnd
 def __init__(self):
     Power.__init__(self)
     self.frequency = "daily"
     self.action = "interrupt"
コード例 #40
0
ファイル: gravis.py プロジェクト: bpittman/pydnd
 def __init__(self):
    Power.__init__(self)
    self.frequency = 'daily'
    self.keywords = ['divine']
コード例 #41
0
sys.path.append('../lib')
sys.path.append('../singleSleeve')
from strip import Strip2D, getAddr
from power import Power

lenx = 7
leny = 21
strips = []
count = 0

addr = getAddr()

for i, address in enumerate(addr):
    s = Strip2D(lenx, leny)
    s.strip.artnet.addr = [address]
    p = Power(s, i * .3)
    strips.append(p)

if False:  # pylint: disable=using-constant-test
    for i, s in enumerate(strips):
        s.auto = True
        thread = threading.Thread(target=s.run, args=[])
        thread.daemon = True
        thread.start()
    while True:
        time.sleep(2)

if True:  # pylint: disable=using-constant-test
    for i, s in enumerate(strips):
        s.auto = False
        s.offset = 13 * i
コード例 #42
0
ファイル: main.py プロジェクト: SpecialWater/Aquatron
class Main:
    load_dotenv()

    def __init__(self):
        # self.URL = "http://192.168.179.227:5001"
        self.URL = "https://pruetpiflask.azurewebsites.net"
        self.token = self.login()
        self.temp_sensor = Temperature()
        self.outlets = Power()
        self.tz = pytz.timezone('US/Central')

        # default state
        self.state = {
            "Temperature": 0,
            "pH": 0,
            "Light_UV_On": True,
            "Light_Refugium_On": True,
            "GasInjection_On": True,
            "Heater_On": True,
            "Pump_Power": 3
        }

        asyncio.run(self.main())

    async def main(self):
        await asyncio.gather(self.iot_hub_login(), self.get_settings())

        # set the mesage received handler on the client
        self.device_client.on_message_received = self.message_received_handler
        loop = asyncio.get_running_loop()
        user_finished = loop.run_in_executor(None, self.stdin_listener)

        # Wait for user to indicate they are done listening for messages
        await user_finished

        # Finally, disconnect
        await self.device_client.disconnect()

    def set_heater_outlet(self):
        if not self.settings["Heater"]["Enabled"]:
            self.outlets.power_off("Heater")
            print("Heater is disabled")
        else:
            min_temp = self.settings["Heater"]["MinTemp"]
            max_temp = self.settings["Heater"]["MaxTemp"]
            current_temp = self.temp_sensor.getTemperature()
            turn_on = True

            if min_temp > current_temp:
                turn_on = True
            elif current_temp > max_temp:
                turn_on = False

            if turn_on:
                self.outlets.power_on("Heater")
            else:
                self.outlets.power_off("Heater")

            print("Temp: {}, Heater On: {}".format(current_temp, turn_on))
            self.state["Heater_On"] = turn_on
            self.state["Temperature"] = current_temp

    def set_timed_outlets(self):
        current_time = datetime.now(self.tz)
        timed_outlets = ["GasInjection", "Light_Refugium", "Light_UV"]

        for outlet in timed_outlets:
            if not self.settings[outlet]["Enabled"]:
                self.outlets.power_off(outlet)
                print("{} is disabled".format(outlet))
            else:
                time_on = self.settings[outlet]["TimeOn"]
                timer = self.settings[outlet]["Timer"]

                turn_on = self.check_timer(current_time, time_on, timer)

                if turn_on:
                    self.outlets.power_on(outlet)
                else:
                    self.outlets.power_off(outlet)

                print("{} turned on: {}".format(outlet, turn_on))
                self.state[outlet + "_On"] = turn_on

    # Check to see if outlet should be turned on or off
    # Applies to CO2, UV light and refugium light
    def check_timer(self, current_time, time_on, timer):
        h_now, m_now = [current_time.hour, current_time.minute]
        h_setting, m_setting = [int(t) for t in time_on.split(":")]
        h_timer, m_timer = [int(t) for t in timer.split(":")]

        minutes_now = h_now * 60 + m_now
        minutes_start = h_setting * 60 + m_setting
        minutes_timer = h_timer * 60 + m_timer
        minutes_end = minutes_start + minutes_timer

        if minutes_start <= minutes_now <= minutes_end:
            return True
        elif (minutes_end >= 1440) and (minutes_now <= minutes_end - 1440):
            return True
        else:
            return False

    def login(self):
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        flask_login = json.dumps({
            "username": os.getenv("FLASK_USERNAME"),
            "password": os.getenv("FLASK_PASSWORD")
        })

        url = self.URL + "/login"
        token = json.loads(
            requests.post(url=url, data=flask_login, headers=headers).text)

        print("Logged in successfully")

        return token

    async def get_settings(self):
        headers = {"Authorization": "Bearer " + self.token["access_token"]}

        url = self.URL + "/settings/get"
        settings = requests.get(url=url, headers=headers)

        self.settings = json.loads(settings.text)
        print("Settings retrieved successfully")

        self.set_timed_outlets()
        self.set_heater_outlet()

    async def iot_hub_login(self):
        try:
            # The client object is used to interact with your Azure IoT hub.
            # module_client = IoTHubModuleClient.create_from_edge_environment()
            # IoTHubModuleClient.create_from_edge_environment()
            conn_str = os.getenv("IOT_CONN_STRING")
            self.device_client = IoTHubDeviceClient. \
                create_from_connection_string(conn_str)

            # connect the client.
            await self.device_client.connect()
            print("Connected to IoTHub")
        except Exception as e:
            print("Unexpected error %s " % e)
            raise

    # define behavior for receiving a message
    # Calls cosmos to get updated settings due to a saved change
    async def message_received_handler(self, message):
        print("the data in the message received was ")
        print(message.data)

        await asyncio.gather(self.get_settings())

        self.post_state()

    def post_state(self):
        headers = {
            "Authorization": "Bearer " + self.token["access_token"],
            'Content-Type': 'application/json'
        }

        url = self.URL + "/state/post"
        payload = json.dumps(self.state)

        settings = requests.post(url=url, data=payload, headers=headers)

    # define behavior for halting the application
    def stdin_listener(self):
        while True:
            self.set_timed_outlets()
            self.set_heater_outlet()
            self.post_state()
            print(self.state, datetime.now())
            time.sleep(60)
コード例 #43
0
ファイル: config-tests.tmp.py プロジェクト: minsuklee/nds-ide
# Add registers like that : reg = Register("NAME")
###############################################################################

###############################################################################
# CAN NETWORK
##########
# Add Can Network if needed
###############################################################################

###############################################################################
# PYGAME WIDGETS
##########
# Add Pygame widgets if needed (for example, a screen which displays several
# information coming from several application
###############################################################################

###############################################################################
# ECUS
##########
# You should always add registers in same order. Else there is an overlap.
###############################################################################
allEcus = [
    Ecu("../check_vp2/functional/SEQUENCE/SEQUENCE_exe", scheduler, [
        Timer("TIMER0", 0, type=timer.AUTO, delay=10),
        ISR("ISR1", 1),
        ISR("ISR2", 2),
        ISR("ISR3", 3),
        Power("POWER", 4),
    ])
]
コード例 #44
0
  [Police2(strip2D),  3],
  [Bump1(strip2D), 3],
  [Police3(strip2D), 3],
  [Lemmings1(strip2D), 10],
  [CMorph(strip2D), 7],
  [Plasma(strip2D), 30],
  [Fire(strip2D), 30],
  [Fire2(strip2D), 30],
  [Night(strip2D), 30],
  [Fade1(strip2D), 3],
  [Fade2(strip2D), 3],
  [Stars1(strip2D), 15],
  [Stars2(strip2D), 10],
  [Hourglass(strip2D), 30],
  [Matrix(strip2D), 20],
  [Power(strip2D), 12],
  [Weird1(strip2D), 12],
  [Weird2(strip2D), 12],
  [Weird3(strip2D), 20],
  [Lighthouse(strip2D), 10],
  [Flash(strip2D), 10],
]


def globalStop(self):
  print( "globalStop" )
  self.artnet.clear()
  self.send()

strip2D.strip.globalStop = globalStop
コード例 #45
0
ファイル: track.py プロジェクト: wx4cb/boresight
class Track:
    def __init__(self, config):
        self.servo_power = Power(config)
        self.servo_power.set_relay_two_off()

        self.degrees_per_radian = 180.0 / math.pi
        self.home = ephem.Observer()
        self.home.lon = config['home']['lng']
        self.home.lat = config['home']['lat']
        self.home.elevation = float(config['home']['alt'])

        self.elements = []

        self.lsm = LSM303DLHC()
        self.lsm.set_declination(10, 40)
        self.servo = Servo(config, self.lsm)

        self.log = logging.getLogger('boresight')
        self._running = True
        self._worker = threading.Thread(target=self._track_worker)
        self._worker.setDaemon(True)
        self._worker.start()

    def exit(self):
        self._running = False
        self.servo.exit()
        self.servo_power.cleanup()

    def set_elements(self, new_elements):
        self.elements = new_elements
        self.log.info("Elements updated.")

    def set_location(self, latitude, longitude, altitude):
        self.home.lon = str(longitude)
        self.home.lat = str(latitude)
        self.home.elevation = altitude

    def get_visible_satellite(self):
        first_sat = Satellite()
        first_element = True
        for index, element in enumerate(self.elements):
            self.home.date = datetime.utcnow()
            sat = ephem.readtle(element[0], element[1], element[2])
            sat.compute(self.home)
            rise_time, rise_azimuth, max_alt_time, max_alt, set_time, set_azimuth = self.home.next_pass(
                sat)
            name = element[0]
            element_index = index

            if (first_element == True
                    or rise_time.datetime() <= first_sat.rise_time.datetime()):
                first_element = False
                first_sat = Satellite(element_index, rise_time, rise_azimuth,
                                      max_alt_time, max_alt, set_time,
                                      set_azimuth, name)
                self.log.info("Found Satellite: %s Rise time: %s azimuth: %s" %
                              (first_sat.name, first_sat.rise_time,
                               first_sat.rise_azimuth))

            self.log.info("Satellite: %s Rise time: %s azimuth: %s" %
                          (name, rise_time, rise_azimuth))
        return first_sat

    def _track_worker(self):
        """
        Runs as a thread
        """
        sleep_interval = 2.0
        get_sat_interval = 120.0
        get_sat_next = time.time()
        satellite = Satellite()

        self.servo.pause_tracking()
        self.servo_power.set_relay_two_on()
        self.servo.park_servos()
        self.servo_power.set_relay_two_off()

        while self._running:
            try:
                if (len(self.elements) > 0):
                    self.log.info('%s: Rise: %s, Azimuth: %s' %
                                  (satellite.name, satellite.rise_time,
                                   satellite.rise_azimuth))
                    if (satellite.rise_time is not None and
                            datetime.utcnow() > satellite.rise_time.datetime()
                            and
                            datetime.utcnow() < satellite.set_time.datetime()):

                        sleep_interval = 0.5
                        self.servo.resume_tracking()
                        self.servo_power.set_relay_two_on()

                        element = self.elements[satellite.element_index]
                        if (len(element) == 3):
                            sat = ephem.readtle(element[0], element[1],
                                                element[2])
                            # iss = ephem.readtle('ISS',
                            # '1 25544U 98067A   15002.52246161  .00016717  00000-0  10270-3 0  9002',
                            # '2 25544  51.6406 190.8516 0006769 204.9577 155.1248 15.52925311  2266'
                            # )
                            self.home.date = datetime.utcnow()
                            sat.compute(self.home)
                            altitude = sat.alt * self.degrees_per_radian
                            azimuth = sat.az * self.degrees_per_radian

                            self.servo.set_high_accuracy(False)
                            self.servo.set_azimuth(azimuth)
                            self.servo.set_elevation(altitude)
                            self.log.info(
                                '%s: altitude % 4.1f deg, azimuth % 5.1f deg' %
                                (element[0], altitude, azimuth))
                    else:
                        sleep_interval = 5.0
                        self.servo.pause_tracking()
                        self.servo.park_servos()
                        self.servo_power.set_relay_two_off()
                        if (time.time() > get_sat_next):
                            get_sat_next = time.time() + get_sat_interval
                            satellite = self.get_visible_satellite()
                            azimuth = satellite.rise_azimuth * self.degrees_per_radian
                            self.servo.set_high_accuracy(False)

            except Exception as inst:
                print type(inst)  # the exception instance
                print inst.args  # arguments stored in .args
                print inst  # __str__ allows args to be printed directly
            time.sleep(sleep_interval)

            # except:
            #    self.log.warn("_track_worker thread exception")
            #    sleep(1)
        self.log.debug("sending thread exit")
コード例 #46
0
ファイル: linder.py プロジェクト: bpittman/pydnd
 def __init__(self):
     Power.__init__(self)
     self.frequency = "encounter"
     self.action = "minor"
コード例 #47
0
ファイル: config.py プロジェクト: minsuklee/nds-ide
###############################################################################
display_server = Server("SERVER")  # uses pygame

###############################################################################
# ECUS
##########
# You should always add registers in same order. Else there is an overlap.
###############################################################################
allEcus = [
    Ecu("../examples/viper2/App-RobotPC/trampoline", scheduler, [
        Network(network_master, "NET0", 0),
        BP("BPFaster", 5, position=[100, 400], text="/\\"),
        BP("BPSlower", 6, position=[100, 480], text="\\/"),
        BP("BPLeft", 7, position=[0, 480], text="<"),
        BP("BPRight", 8, position=[200, 480], text=">"),
        Power("POWER", 9),
    ]),
    Ecu("../examples/viper2/App-Robot1/trampoline", scheduler, [
        Network(network_master, "NET1_1", 0),
        Timer("TIMER0", 1, type=timer.AUTO, delay=100),
        DisplayServer("LCD1", 2, display_server),
        Motor("MOTOR1_1", 3),
        Motor("MOTOR1_2", 4),
        Network(network_slave, "NET1_2", 5),
        Power("POWER", 9),
    ]),
    Ecu("../examples/viper2/App-Robot2/trampoline", scheduler, [
        Network(network_slave, "NET2", 0),
        Timer("TIMER0", 1, type=timer.AUTO, delay=100),
        DisplayServer("LCD2", 2, display_server),
        Motor("MOTOR2_1", 3),
コード例 #48
0
def run_game():
    print 'game ran'
    pygame.init()
    game_settings = Settings()
    game_start_time = time.time()
    real_game_start_time = time.time()
    # create a tuple for the screen size
    screen = pygame.display.set_mode(game_settings.screen_size)
    pygame.display.set_caption('a heroic pygame shooter')
    the_hero = Hero('images/Hero.png', screen)
    hero_group = Group()
    hero_group.add(the_hero)
    bullets = Group()
    enemies = Group()
    background = Background('images/background.png', screen)
    power = Power('images/react.png', screen)
    powers = Group()
    power2 = Power('images/redux.png', screen)
    powers2 = Group()
    bullet_level = 1

    def add_enemy():
        enemies.add(Enemy(screen, game_settings, 1, 'front', 3))
        enemies.add(Enemy(screen, game_settings, 2, 'front', 3))
        enemies.add(Enemy(screen, game_settings, 3, 'front', 3))
        enemies.add(Enemy(screen, game_settings, 4, 'front', 3))
        enemies.add(Enemy(screen, game_settings, 5, 'front', 3))
        enemies.add(Enemy(screen, game_settings, 1, 'front1', 3))
        enemies.add(Enemy(screen, game_settings, 2, 'front1', 3))
        enemies.add(Enemy(screen, game_settings, 3, 'front1', 3))
        enemies.add(Enemy(screen, game_settings, 4, 'front1', 3))
        enemies.add(Enemy(screen, game_settings, 5, 'front1', 3))

    def add_enemy1():
        enemies.add(Enemy(screen, game_settings, 1, 'mid', 3))
        enemies.add(Enemy(screen, game_settings, 2, 'mid', 3))
        enemies.add(Enemy(screen, game_settings, 3, 'mid', 3))
        enemies.add(Enemy(screen, game_settings, 4, 'mid', 3))
        enemies.add(Enemy(screen, game_settings, 5, 'mid', 3))

    def add_enemy2():
        enemies.add(Enemy(screen, game_settings, 1, 'mid1', 3))
        enemies.add(Enemy(screen, game_settings, 2, 'mid1', 3))
        enemies.add(Enemy(screen, game_settings, 3, 'mid1', 3))
        enemies.add(Enemy(screen, game_settings, 4, 'mid1', 3))
        enemies.add(Enemy(screen, game_settings, 5, 'mid1', 3))

    def add_enemy3():
        enemies.add(Enemy(screen, game_settings, 1, 'back', 3))
        enemies.add(Enemy(screen, game_settings, 2, 'back', 3))
        enemies.add(Enemy(screen, game_settings, 3, 'back', 3))
        enemies.add(Enemy(screen, game_settings, 4, 'back', 3))
        enemies.add(Enemy(screen, game_settings, 5, 'back', 3))

    def add_enemy4():
        enemies.add(Enemy(screen, game_settings, 1, 'back1', 3))
        enemies.add(Enemy(screen, game_settings, 2, 'back1', 3))
        enemies.add(Enemy(screen, game_settings, 3, 'back1', 3))
        enemies.add(Enemy(screen, game_settings, 4, 'back1', 3))
        enemies.add(Enemy(screen, game_settings, 5, 'back1', 3))

    game_on = True
    add_enemy()
    while 1:

        if game_settings.game_active:
            game_settings.real_timer = int(time.time() - real_game_start_time)
            reset_time = 0
            if game_settings.real_timer > 120: reset_time = 4
            elif game_settings.real_timer > 100: reset_time = 5
            elif game_settings.real_timer > 80: reset_time = 6
            elif game_settings.real_timer > 60: reset_time = 7
            elif game_settings.real_timer > 40: reset_time = 8
            elif game_settings.real_timer > 20: reset_time = 9
            else: reset_time = 11

            game_settings.timer = int(time.time() - game_start_time)
            if (game_settings.timer) > reset_time:
                enemies = Group()
                add_enemy()
                add_enemy1()

                if game_settings.real_timer in range(19, 26):
                    powers.add(power)
                if game_settings.real_timer > 29:
                    add_enemy2()

                    if game_settings.real_timer > 41:
                        add_enemy3()
                        # if game_settings.real_timer in range(44, 50):
                        powers2.add(power2)
                        bullets = Group()
                        if game_settings.real_timer > 51:
                            add_enemy4()

                game_start_time = time.time()
            kill_enemy = False
            if bullet_level == 3:
                kill_enemy = groupcollide(enemies, bullets, False, False)
            else:
                kill_enemy = groupcollide(enemies, bullets, False, True)
            for enemy in kill_enemy:
                enemy.hit(1)
                if enemy.health <= 0:
                    enemies.remove(enemy)
                    game_settings.ninjas_killed += 1

            kill_hero = groupcollide(hero_group, enemies, True, True)
            if kill_hero:
                game_on = False
            power_up = groupcollide(hero_group, powers, False, True)
            power_up2 = groupcollide(hero_group, powers2, False, True)
            # print powers.len()
            if power_up2: bullet_level = 3
            elif power_up: bullet_level = 2
            # if kill_enemy:
            # kill_enemy2 = groupcollide(bullets, enemies, True, True);

            check_events(screen, the_hero, game_settings, bullets,
                         bullet_level, enemies)
            update_screen(screen, hero_group, game_settings, bullets, enemies,
                          background, powers, powers2, the_hero)
            # while not game_on:
            # time.sleep(1)
            print bullet_level