def _configure_triggers(self, data): for trig in self._triggers: trig.reset_configuration() self._triggers.clear() for elem in data: # print(elem) simvar = elem.get('simvar') trigger_type = elem.get('trigger_type', None) trigger_index = elem.get('trigger_index', None) condition = elem.get('condition', None) object_to_trigger = None trigger = Trigger() trigger.bind_to_simvar(simvar) if trigger_type == "encoder": object_to_trigger = self._encoders[trigger_index - 1] trigger.bind_to_event(object_to_trigger.on_alternate) elif trigger_type == "button": object_to_trigger = self._buttons[trigger_index - 1] elif trigger_type == "condition": trigger.bind_to_event(ConditionalRunner(condition)) elif trigger_type == "condition-file": trigger.bind_to_event(ConditionalRunner("", condition)) else: raise ValueError(f"Unknown trigger type: {trigger_type}") self._triggers.append(trigger)
def main (args, app): new_trigger = Trigger(name=args.name, then=' '.join(args.then)) if not args.preview: new_trigger.store(app.config) app.config.save( ) print "added", new_trigger.format_url( )
def decorator(trigger_function): """This takes the trigger's associated function as the only argument It defines the decorator and wrapper, as well as setting up the 'Trigger' object and associating it with the decorated function. """ if 'name' not in t_kwargs: # No name for this trigger was provided; use trigger's function name t_kwargs['name'] = trigger_function.__name__ # Create an instance of the 'Trigger' class new_trigger = Trigger( *t_args, **t_kwargs ) # provide all wrapper arguments to this 'trigger' instance def wrapper(*args, **kwargs): """This function is what will be called in place of the decorated function; It takes the arguments given to it and passes them on. It needs to run said function and return what it does or (if it doesn't return anything), return the value of the stop_processing flag in the trigger class """ r = trigger_function( *args, **kwargs) # call the original trigger function return r or new_trigger.stop_processing new_trigger.add_function( wrapper) # Associate the wrapper with the trigger object # add the trigger to an internal list self.triggers.append(new_trigger) return wrapper
def __init__(self): """ connect hardware, initialize state dir """ self.trigger = Trigger() self.display = Display() self.current_address = None self.cost = 0 self.set_state(Vend.STARTUP)
def make_switch_collision(self, switch_group, image, starting_x, x_copies, starting_y, y_copies, function): for x in range(x_copies): for y in range(y_copies): path_piece = Trigger(4, (starting_x*32) + (x*32), (starting_y*32) +(y*32)) path_piece.image = image switch_group[0].add(path_piece) switch_group[1].append((path_piece, function))
def make_collision(self, image, starting_x, x_copies, starting_y, y_copies, function): for x in range(x_copies): for y in range(y_copies): collision = Trigger(3, (starting_x*32) + (32*x), (starting_y*32) + (32*y)) collision.image = image self.drawables.append(collision) self.collisions.append((collision, function))
def __init__(self, trigger, filter=Filter(), action=Action(), name=""): """Create a new rule given a trigger, a filter and an action We can give a list of action or a list of filter instead of a single action or filter, in that case the actions will be turned into a ListAction and the filters into an AndFilter. """ Trigger.__init__(self) Action.__init__(self) # We accept list OR single value as argument if isinstance(filter, list): filter = AndFilter(*filter) if isinstance(action, list): action = ListAction(action) assert isinstance(trigger, Trigger) assert isinstance(action, Action) assert isinstance(filter, Filter) self.__trigger = trigger # The trigger will call this rule when triggered trigger.connect(self) self.__filter = filter self.__action = action self.connect(action) self.name = name
def damage(cls, target, amount, actor=None): from trigger import Trigger target.hp -= amount target.save() print "damage:",amount,"target:",target,"hp left:",target.hp Trigger.invoke_triggers(target, "receive damage") if actor: Trigger.invoke_triggers(actor, "deal damage")
def make_bridge(self): "Creates the bridge once the player triggers it" self.now = pygame.time.get_ticks() if self.now - self.last_switch > 1000: self.add_flag = True bridge = [] for i in range(3): for j in range(6): bridge.append(league.DUGameObject) bridge[i + j] = Trigger(3, 352 + (32 * i), 160 + (32 * j)) bridge[i + j].image = self.sprites_base.sprites[248].image self.drawables.append(bridge[i+j]) self.last_switch = pygame.time.get_ticks()
def next_round(self): from main.utils import distribute self.turn += 1 self.save() for hero in self.heros(): hero.combat_messages.append([]) hero.save() combatants = Combatant.objects.filter(combat=self, alive=True).all() magerys = map(lambda s: s.__getattribute__("magery"), combatants) num_mp = 5 * len(combatants) mp_gains = distribute(num_mp, magerys) for i in xrange(len(combatants)): combatants[i].mp = min(combatants[i].max_mp, combatants[i].mp + mp_gains[i]) combatants[i].save() Trigger.invoke_triggers(combatants[i], "end of round")
def read_map(game, m: str = 'map'): with open(m, 'r') as m: m = json.loads(m.read()) if 'Start' in m: game.start = m['Start'] if 'Platforms' in m: game.platforms.clear() for p in m['Platforms']: game.platforms.append( Platform(*x_to_pixels(game, p['x1'], p['x2']), *y_to_pixels(game, p['y1'], p['y2']))) if 'Triggers' in m: game.triggers.clear() for t in m['Triggers']: game.triggers.append( Trigger(*x_to_pixels(game, t['x1'], t['x2']), *y_to_pixels(game, t['y1'], t['y2']), t['enter'], t['stay'], t['leave'])) if 'Windows' in m: for w in game.windows.values(): w.close() game.windows = {} for w in m['Windows']: win = Window( w['name'], w['effect'], w['function'], game, style=pyglet.window.Window.WINDOW_STYLE_BORDERLESS, width=x_to_pixels(game, w['width']), height=y_to_pixels(game, w['height']), visible=w['visible']) game.windows[w['name']] = win
def main(args, app): for trigger in Trigger.FromConfig(app.config): if args.name == trigger.name: trigger.remove(app.config) app.config.save() print 'removed', trigger.format_url() break
def process(start_url): u = url_manage(start_url) w = Website() process_func = w.qq_news_process t = Trigger(slot) trigger_func = t.url_trigger p = post_proc("../data/result.csv") post_proc_func = p.save_result_process conf = SparkConf().setMaster("local[8]").setAppName("Crawler") sc = SparkContext(conf=conf) while 1: if trigger_func(u): urls = sc.parallelize(u.get_url_queue()) results = urls.map(process_func) print results.collect() for res, url in zip(results.collect(), urls.collect()): print res, url post_proc_func(res, url, u) time.sleep(1) sc.stop()
def execute(bot, data, forward=True): args = { "peer_id": data['peer_id'], "v": "5.60", } if forward: args.update({"forward_messages": data['message_id']}) atts = data['attachments'] try: photo = bot.GetBiggesPic(atts[0], data['message_id']) except: return False req = urllib.request.Request(photo, headers=HDR) img = urlopen(req).read() Tmp = TempFile(img, 'jpg', NoCache=True) args['message'] = 'Список фильтров:\n' FArr = dict(enumerate(bot.MODULES.FILTERS)) for filter_ in FArr: Fname = bot.MODULES.FILTERS[FArr[filter_]].desc args['message'] += "{}. {}\n".format(filter_ + 1, Fname) bot.Replyqueue.put(args) print(data['user_id'], data['peer_id']) t = Trigger( cond=lambda Tdata: Tdata['user_id'] == data['user_id'] and Tdata[ 'peer_id'] == data['peer_id'] and Tdata['message'].isnumeric(), callback=Command_Filter.Render, Tmp=Tmp, bot=bot, args=args, FArr=FArr) bot.TRIGGERS.addTrigger(t)
def __init__(self, useRPi): """ :param useRPi: Flag for using Raspberry pi or pc """ threading.Thread.__init__(self) self._useRPi = useRPi # Instantiates subsystems self._camera = Camera(self._useRPi) self._processor = Processor(self) self._trigger = Trigger(self._useRPi) self._imageregister = Imageregister() # Mask handling flags self._applymask = False self._invertedmask = False self._binarymask = False self.savemaskedon = False
def main (args, app): for trigger in Trigger.FromConfig(app.config): if args.name == trigger.name: with SystemBus( ) as bus: path = PATH + '/EventSink/{name:s}'.format(name=trigger.name) event = bus.get(BUS, path) event.Fire( ) props = event.GetAll(OWN_IFACE) print props
def load_triggers(self): logging.info("Loading triggers") self.triggers = {} n = 0 cn = 0 ec = [(c.name, c.id) for c in AlarmClass.objects.all()] for t in AlarmTrigger.objects.filter(is_enabled=True): logging.debug("Trigger '%s' for classes:" % t.name) for c_name, c_id in ec: if re.search(t.alarm_class_re, c_name, re.IGNORECASE): try: self.triggers[c_id] += [Trigger(t)] except KeyError: self.triggers[c_id] = [Trigger(t)] cn += 1 logging.debug(" %s" % c_name) n += 1 logging.info("%d triggers has been loaded to %d classes" % (n, cn))
def create_room(self, x=1, y=1): room = Room(self.room_size) for i in range(self.room_size): block_width = self.width block_height = self.height block_x = (x * self.room_size + i * i) * block_width block_y = round((i * math.sin(y * self.room_size + i) * block_width) + (y * self.room_size + 0) * block_height) room.blocks.append( Block(block_x, block_y, block_width, block_height, '/images/ground.png').convert_to_json()) block_x = (x * self.room_size + i) * block_width block_y = round((random.randint(0, self.room_size) * math.sin(y * self.room_size + i) * block_width) + (y * self.room_size + 0) * block_height) room.blocks.append( Block(block_x, block_y, block_width, block_height, '/images/ground.png').convert_to_json()) block_x = random.randint(x * block_width, x * self.room_size * block_width) block_y = random.randint(y * block_width, y * self.room_size * block_width) room.blocks.append( Bonus(block_x, block_y, block_width, block_height).convert_to_json()) block_x = random.randint(x * block_width, x * self.room_size * block_width) block_y = random.randint(y * block_width, y * self.room_size * block_width) teleport = Trigger(block_x, block_y, block_width, block_height, "teleport") room.blocks.append(teleport.convert_to_json()) return {'blocks': room.blocks}
def main(): ''' Test LED Blink Red Solid Red Blink Green Solid Green Test Trigger Push trigger Hold trigger Test Send fake IR code Listen for callback ''' led = LED() print("Testing LEDs.\n") eventOne = threading.Event() threadOne = threading.Thread(name='ledOnRed', target=setLED, args=(eventOne, 'red', led, 1)) threadOne.start() answer = input("Is the Red LED on? y/n: ") eventOne.set() if not answer.lower() == 'y': return False eventTwo = threading.Event() threadTwo = threading.Thread(name='ledBlinkRed', target=toggleLED, args=(eventTwo, 'red', led, 1)) threadTwo.start() answer = input("Is the Red LED blinking? y/n: ") # Get user input. eventTwo.set() if not answer.lower() == 'y': return False eventThree = threading.Event() threadThree = threading.Thread(name='ledOnGreen', target=setLED, args=(eventThree, 'green', led, 1)) threadThree.start() answer = input("Is the Green LED on? y/n: ") eventThree.set() if not answer.lower() == 'y': return False eventFour = threading.Event() threadFour = threading.Thread(name='ledBlinkGreen', target=toggleLED, args=(eventFour, 'green', led, 1)) threadFour.start() answer = input("Is the Green LED blinking? y/n: ") # Get user input. eventFour.set() if not answer.lower() == 'y': return False trigger = Trigger() print("Push and hold the trigger for 10 events.") i = 0 while i < 10: if GPIO.input(trigger.TRIGGER) == GPIO.HIGH: time.sleep(0.1) print(("{}: Trigger detected.").format(datetime.datetime.now())) i += 1 time.sleep(1) print("LaserPi programmed remote codes:") call(["irsend", "LIST", "laserpi", ""]) return True
def main (args, app): wait = WaitApp( ) for trigger in Trigger.FromConfig(app.config): if args.name == trigger.name: with SystemBus( ) as bus: path = PATH + '/EventSink/{name:s}'.format(name=trigger.name) event = bus.get(BUS, path) props = event.GetAll(OWN_IFACE) print props wait.until(event, timeout=args.seconds) if wait.expired: sys.exit(2)
def main(): trigger = Trigger(TriggerType.PROC_NAME, 'notepad.exe', custom) # port_action = Action(TriggerType.CON_PORT, 443, custom) # ip_action = Action(TriggerType.CON_IP, '23.213.175.172', custom) lock = Locker(panic=False, panic_pass='******', debug=True) #set up your Locker # lock.actions = port_action # lock.actions = ip_action # lock.private_exes = 'secret.exe' #append more exes # lock.private_exes = ['slack.exe', 'excel.exe'] #lists are ok too # lock.private_paths = '/user' lock.triggers = trigger lock.run()
def make_north_door(self, next_screen): """Creates and places a trigger for the north door that loads the next screen at the connecting south door""" screen_trigger = Trigger(3, 352, 0) screen_trigger.image = self.sprites_utu.sprites[1094].image self.drawables.append(screen_trigger) self.collisions.append((screen_trigger, next_screen)) screen_trigger = Trigger(3, 384, 0) screen_trigger.image = self.sprites_utu.sprites[1094].image self.drawables.append(screen_trigger) self.collisions.append((screen_trigger, next_screen))
def make_west_door(self, next_screen): """Creates and places a trigger for the west door that loads the next screen at the connecting east door""" screen_trigger = Trigger(3, 0, 288) screen_trigger.image = self.sprites_utu.sprites[1096].image self.drawables.append(screen_trigger) self.collisions.append((screen_trigger, next_screen)) screen_trigger = Trigger(3, 0, 320) screen_trigger.image = self.sprites_utu.sprites[1096].image self.drawables.append(screen_trigger) self.collisions.append((screen_trigger, next_screen))
def make_south_door(self, next_screen): """Creates and places a trigger for the south door that loads the next screen at the connecting north door""" screen_trigger = Trigger(3, 352, 608) screen_trigger.image = self.south_door_image self.drawables.append(screen_trigger) self.collisions.append((screen_trigger, next_screen)) screen_trigger = Trigger(3, 384, 608) screen_trigger.image = self.south_door_image self.drawables.append(screen_trigger) self.collisions.append((screen_trigger, next_screen))
def set_screen_cliffs(self): """Creates 'cliffs' screen""" self.background = league.Tilemap('../assets/cliffs_background.lvl', self.sprites_utu, layer=1) self.terrain = league.Tilemap('../assets/cliffs_terrain.lvl', self.sprites_base, layer=2) self.details = league.Tilemap('../assets/cliffs_details.lvl', self.sprites_utu, layer=3) self.drawables.append(self.background.passable.sprites()) self.drawables.append(self.terrain.passable.sprites()) self.drawables.append(self.details.passable.sprites()) "Loads north door sprites leading to 'lost woods entrance' south door" self.make_north_door(self.lost_woods_entrance_door_south) "Loads south door sprites leading to 'hills' north door" self.make_south_door(self.grassland_door_north) "Loads the switch sprite for the bridge" bridge_switch = Trigger(3, 500, 480) bridge_switch.image = self.sprites_base.sprites[70].image self.drawables.append(bridge_switch) self.collisions.append((bridge_switch, self.make_bridge)) bridge_switch = Trigger(3, 500, 50) bridge_switch.image = self.sprites_base.sprites[70].image self.drawables.append(bridge_switch) self.collisions.append((bridge_switch, self.make_bridge)) "Makes the area where the bridge will be impassable. Removed by make_bridge to make passable" bridge_block = [] for i in range(3): for j in range(7): bridge_block.append(league.DUGameObject) bridge_block[i + j] = Trigger(1, 352 + (32 * i), 128 + (32 * j)) bridge_block[i + j].image = self.sprites_base.sprites[97].image self.drawables.append(bridge_block[i + j]) self.blocking_object.add(bridge_block[i+j]) "Sets update() to change screens" self.change_flag = True
def __init__(self, name: str, effect, fcn: Union[str, None], game, *args, visible=True, **kwargs): super().__init__(*args, **kwargs) self.game = game self.set_visible(visible) self.set_caption(name) self.set_location(0, 0) self.x1 = self.get_location()[0] self.x2 = self.get_location()[0] + self.width self.y1 = self.get_location()[1] self.y2 = self.get_location()[1] + self.height self.name = name self.color = effects[effect[0]][1] self.effect = lambda game, obj, state: effects[effect[0]][0]( game, obj, state, **effect[1]) self.trigger = Trigger(self.x1, self.x2, self.y1, self.y2, enter=('effect', { 'effect': self.effect, 'state': 'enter' }), stay=('effect', { 'effect': self.effect, 'state': 'stay' }), leave=('effect', { 'effect': self.effect, 'state': 'leave' })) if effect != 'None': self.game.triggers.append(self.trigger) self.moving = False self.on_close = lambda: None self.fcn = lambda game: movements[fcn[0]](game, **fcn[1]) if fcn[ 0] else movements['static'](game)
def execute(bot, data, forward=True): args = { "peer_id": data['peer_id'], "v": "5.60", } if forward: args.update({"forward_messages": data['message_id']}) atts = data['attachments'] if 'size' in data['custom']: x = int(data['custom']['size']) if x > 3000: args['message'] = "Неее, слишком жирно" bot.Replyqueue.put(args) return False else: args['message'] = "Размер не указан" bot.Replyqueue.put(args) return False Topost = [] for att in atts: try: photo = bot.GetBiggesPic(att, data['message_id']) except: return False req = urllib.request.Request(photo, headers=HDR) img = urlopen(req).read() Tmp = TempFile(img, 'jpg', NoCache=True) args['message'] = 'Поднимать резкость?\n Да\Нет' bot.Replyqueue.put(args) ans = bot.WaitForMSG(5, data) t = Trigger(cond=lambda Tdata: Tdata['user_id'] == data[ 'user_id'] and Tdata['peer_id'] == data['peer_id'] and (re.match(r'(Д|д)а', Tdata['message']) or re.match( r'(Н|н)ет', Tdata['message'])), callback=Command_Resize.resize, Tmp=Tmp, bot=bot, args=args) bot.TRIGGERS.addTrigger(t)
#!/bin/env python import signal import sys import time from trigger import Trigger trigger = Trigger() def signal_handler(signal, frame): trigger.reset() sys.exit(0) signal.signal(signal.SIGINT, signal_handler) trigger.pre_shoot() n_bullets = int(sys.argv[1]) while True: trigger.shoot(n_bullets) time.sleep(1 * n_bullets)
print cmd.__class__.__name__ Trigger.call(cmd, "email") except Exception, e: # print the stacktrace tb = sys.exc_info()[2] stacktrace = traceback.format_tb(tb) stacktrace_str = "".join(stacktrace) print "-"*50 print stacktrace_str print str(e) print "-"*50 raise """ # call all registered triggers Trigger.call_all_triggers() execute_cmd = classmethod(execute_cmd) def is_undoable(cls): return True is_undoable = classmethod(is_undoable) # Is now part of command ... may change later #class ProcessCommand(Command): '''These commands must be run under a process in a pipeline. In effect, this pipeline owns the command that was executed. ''' def set_process(my, process_name):
######################################################################### ###################################### # Initialize screen, logger and inputs logging.basicConfig( level=CONF["loggingLevel"], format='%(asctime)s-%(levelname)s-%(message)s', ) # This is a log for debugging the script, and prints messages to the terminal # needs to be first, so that if it doesn't succeed, it doesn't freeze everything eyetracker = PupilCore(ip=CONF["pupillometry"]["ip"], port=CONF["pupillometry"]["port"], shouldRecord=CONF["recordEyetracking"]) trigger = Trigger(CONF["trigger"]["serial_device"], CONF["sendTriggers"], CONF["trigger"]["labels"]) screen = Screen(CONF) datalog = Datalog(OUTPUT_FOLDER=os.path.join( 'output', CONF["participant"] + "_" + CONF["session"], datetime.datetime.now().strftime("%Y-%m-%d")), CONF=CONF) # This is for saving data kb = keyboard.Keyboard() mainClock = core.MonotonicClock() # starts clock for timestamping events alarm = sound.Sound(os.path.join('sounds', CONF["instructions"]["alarm"]), stereo=True)
################# I want this for when we do the mounting stuff###################### # save_directory = "/mnt/nfsserver/videos" # mv_directory = "/mnt/nfsserver/videos" # should be the same as save directory for pi_master # #the following mount only applies if pi_master is set false (if this is slavepi) # directory_to_mount = "192.168.0.3:/mnt/nfsserver" # mount_location = "/mnt/nfs" # if not pi_master: # nfs_mount(directory_to_mount, mount_location) # save_directory = "/home/nick/videos" # mv_directory = "/mnt/nfs/videos" ##################################################################################### if __name__ == "__main__": camera = picamera.PiCamera() trigger = Trigger() green_led = Led(green_led_pin) red_led = Led(red_led_pin) file_name = save_name.File_namer(mv_directory,save_directory, device) running = True while running: try: red_led.led_off() green_led.led_on() trigger.read_state() if trigger.input_state == False: print "recording..." + file_name.get_name() green_led.led_off() red_led.led_on() camera.start_recording(file_name.get_name())
def generic_attack(cls, actor, target, stats={}): ''' returns damage dealt (None on miss) case accuracy: 'Inf', attack hits, None: attack misses, else: roll some dice case critical: 'Inf', critical hit, None: normal damage, else: roll some dice case exact_damage: None: roll some dice, else: damage = exact_damage ''' import random, math from trigger import Trigger DEFAULT_STATS = { "accuracy": actor.finesse, "critical": actor.lore, "exact_damage": None, "might": actor.brawn, "weapon": 3, #actor.weapon_power "plus_damage": 0, } stats_in = stats stats = DEFAULT_STATS.copy() stats.update(stats_in) #print "actor:", actor, "target:", target #print "stats:", stats Trigger.invoke_triggers(target, "receive attack") Trigger.invoke_triggers(actor, "deal attack") if (stats['accuracy'] != None) and (float(stats['accuracy']) * 2.0 / 3.0 / target.charm >= random.random()): Trigger.invoke_triggers(target, "receive hit") Trigger.invoke_triggers(actor, "deal hit") else: Trigger.invoke_triggers(target, "receive miss") Trigger.invoke_triggers(actor, "deal miss") return None if stats['exact_damage'] == None: damage = int(math.ceil(stats['might'] * stats['weapon'] * (0.8 + 0.4 * random.random()) / target.stamina)) damage += stats['plus_damage'] else: damage = stats['exact_damage'] if damage > 0: if stats['critical'] != None: if 0.25 * (float(stats['critical'])-target.lore)/target.lore >= random.random(): damage = int(math.ceil(damage * 1.5)) Action.damage(target, damage) else: damage = 0 return damage
print cmd.__class__.__name__ Trigger.call(cmd, "email") except Exception, e: # print the stacktrace tb = sys.exc_info()[2] stacktrace = traceback.format_tb(tb) stacktrace_str = "".join(stacktrace) print "-"*50 print stacktrace_str print str(e) print "-"*50 raise """ # call all registered triggers Trigger.call_all_triggers() execute_cmd = classmethod(execute_cmd) def is_undoable(cls): return True is_undoable = classmethod(is_undoable) # Is now part of command ... may change later #class ProcessCommand(Command): '''These commands must be run under a process in a pipeline. In effect, this pipeline owns the command that was executed. '''
from trigger import Trigger from psychopy import core from config import CONF trigger = Trigger(CONF["trigger"]["serial_device"], CONF["sendTriggers"], CONF["trigger"]["labels"]) n = 500 for i in range(1, n): trigger.send(i) core.wait(1)
def set_attack_enemy_stepping_next_to_me(entity): trigger_effect = Composite("set_attack_enemy_stepping_next_to_me") trigger_effect.set_child(Trigger([ENEMY_STEPPING_NEXT_TO_ME_TRIGGER_TAG])) trigger_effect.set_child(AttackEnemyTriggeredEffect(DataTypes.DEFENCIVE_ATTACK_CHANCE)) entity.set_child(trigger_effect)
def set_attack_enemy_i_step_next_to(entity): trigger_effect = Composite("attack_enemy_i_step_next_to") trigger_effect.set_child(Trigger([STEP_NEXT_TO_ENEMY_TRIGGER_TAG])) trigger_effect.set_child(AttackEnemyTriggeredEffect(DataTypes.OFFENCIVE_ATTACK_CHANCE)) entity.set_child(trigger_effect)
class Vend(object): # display states (screens) STARTUP = 0 READY = 1 SALE = 2 TXREFUND = 3 SHUTDOWN = 4 def __init__(self): """ connect hardware, initialize state dir """ self.trigger = Trigger() self.display = Display() self.current_address = None self.cost = 0 self.set_state(Vend.STARTUP) def get_listeners(self): return ('tx', self.ix.recv_tx, 'ix', self.ix.recv_ix, 'txlvote', self.ix.recv_votes, 'block', self.recv_block) def set_instantx(self, ix): ix.set_vend(self) self.ix = ix def set_dashrpc(self, dashrpc): self.dashrpc = dashrpc # payment processing def set_address_chain(self, bip32): """ attach pycoin key instance """ self.bip32 = bip32 self.get_next_address() def get_next_address(self, increment=False): """ payment address to monitor """ self.current_address = self.bip32.get_next_address(increment) self.ix.set_watch_address(self.current_address) def set_product_cost(self, cost): """ set required float value to trigger sale """ # convert to duffs self.cost = int(cost * 1e8) # vending processing def trigger_sale(self): self.set_state(Vend.SALE) self.trigger.trigger() Timer(15, lambda: self.set_state(Vend.READY), ()).start() def show_txrefund(self): self.set_state(Vend.TXREFUND) Timer(10, lambda: self.set_state(Vend.READY), ()).start() def set_state(self, state): self.state = state self.display.show_screen_number( self.state, self.current_address, float(self.cost / 1e8)) # refunds processing def recv_block(self, msg): """ process tx refunds at each new block """ info(" --> new block: %s" % self.dashrpc._proxy.getblockcount()) self._process_refunds(msg) def _process_refunds(self, msg): # noqa for txid in self.ix.mempool: # TODO check block contains tx payment to be refunded if 'refunded' in self.ix.mempool[txid]: continue if 'processed' in self.ix.mempool[txid]: if self.ix.mempool[txid]['processed']['refund'] > 0: p = self.ix.mempool[txid]['processed'] refund_addr = self.select_return_address(txid) info(' --> refunding %s to %s' % (p['refund'], refund_addr)) # noqa self.sendtoaddress(refund_addr, p['refund']) p['refunded'] = True for txid in self.ix.mempool.keys(): # delete completed (sold/refunded) mempool entries if 'processed' in self.ix.mempool[txid]: p = self.ix.mempool[txid]['processed'] if ('refunded' in p or 'sold' in p): label = ' + '.join( [i for i in ( 'sale' in p and 'SALE', 'refunded' in p and 'REFUND' ) if i]) debug(" --> deleting processed mempool txid: %s -- %s" % (txid, label)) # noqa del self.ix.mempool[txid] # delete non-target cached votes after 1 minute elif 'recv_time' in self.ix.mempool[txid]: # keep pending refunds in queue (insufficient funds) if 'processed' in self.ix.mempool[txid]: if ('refund' in self.ix.mempool[txid]['processed'] and self.ix.mempool[txid]['processed']['refund'] > 0): continue if int(time.time()) - self.ix.mempool[txid]['recv_time'] > 60: debug(" --> deleting stale mempool txid: %s" % txid) del self.ix.mempool[txid] def sendtoaddress(self, addr, amount): p = self.dashrpc._proxy try: p.sendtoaddress(addr, amount) except JSONRPCException: warn("**********************************************************") warn("INSUFFICIENT FUNDS TO PROCESS REFUND/BOUNCE FOR") warn(" %s to %s " % (amount, addr)) warn(" wallet balance: %s" % (p.getbalance())) warn("**********************************************************") def get_txn(self, txid): p = self.dashrpc._proxy return p.decoderawtransaction(p.getrawtransaction(txid)) def select_return_address(self, txid): prevout = self.get_txn(txid)[u'vin'][0] source = self.get_txn(prevout[u'txid'])[u'vout'] return source[prevout[u'vout']][u'scriptPubKey'][u'addresses'][0]
def run(self): # while xbmc is running trigger = Trigger() while not (self.abortRequested or xbmc.abortRequested): try: tn = telnetlib.Telnet("localhost", 9090, 10) except IOError as (errno, strerror): # connection failed, try again soon Debug("[Notification Service] Telnet too soon? (" + str(errno) + ") " + strerror) time.sleep(1) continue Debug("[Notification Service] Waiting~") bCount = 0 while not (self.abortRequested or xbmc.abortRequested): try: if bCount == 0: notification = "" inString = False [index, match, raw] = tn.expect( ['(\\\\)|(\\")|[{"}]'], 0.2 ) # note, pre-compiled regex might be faster here notification += raw if index == -1: # Timeout continue if index == 0: # Found escaped quote match = match.group(0) if match == '"': inString = not inString continue if match == "{": bCount += 1 if match == "}": bCount -= 1 if bCount > 0: continue if bCount < 0: bCount = 0 except EOFError: break # go out to the other loop to restart the connection Debug("[Notification Service] message: " + str(notification)) # Parse recieved notification data = json.loads(notification) # Forward notification to functions if ( "method" in data and "params" in data and "sender" in data["params"] and data["params"]["sender"] == "xbmc" ): if data["method"] == "Player.OnStop": Debug("[HATrigger] Stopped Playback") trigger.playbackEnded() elif data["method"] == "Player.OnPlay": if ( "data" in data["params"] and "item" in data["params"]["data"] and "id" in data["params"]["data"]["item"] and "type" in data["params"]["data"]["item"] ): Debug("[HATrigger] Started Playback") trigger.playbackStarted(data["params"]["data"]) elif data["method"] == "Player.OnPause": Debug("[HATrigger] Paused Playback") trigger.playbackPaused() elif data["method"] == "System.OnQuit": self.abortRequested = True time.sleep(1)