def switchoff(): socket = int(request.query.socket) if (socket >= 0 and socket <= 4): #print 'Switching off {}'.format(socket) switch_off(socket) if (socket == 0): return 'Requested switch off ALL' else: return 'Requested switch off {}'.format(socket)
def switchoff(): socket = int(request.query.socket) if (socket >= 0 and socket <= 4) : #print 'Switching off {}'.format(socket) switch_off (socket) if (socket == 0) : return 'Requested switch off ALL' else : return 'Requested switch off {}'.format(socket)
def send_control(control): if control: for i in range(3): switch_on() sleep(1) else: for i in range(3): switch_off() sleep(1)
def light_controller(timeOff): switch_on(0) print "Turning on light now and going to sleep" print(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S")) time.sleep(timeOff) print "Good morning, turning off the light" print(datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S")) switch_off(0) print "I have finished running" return
def light_controller(): switch_off(0) logger = logging.getLogger('plantie') hdlr = logging.FileHandler('/home/plantie/scripts/plantie.log') formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.INFO) logger.info('Plantie has switched off') return
def toggle_lights(key, state): """Toggle lights.""" log.info("Toggling lights {} for key {}".format(state, key)) for attempt in range(3): log.info("Attempt {} of 3: Sending '{}' command to switch {}..." .format(attempt, state, key)) if state == 'on': switch_on(key) elif state == 'off': switch_off(key) time.sleep(1)
def main(): a = Astral() a.solar_depression = 'civil' city = a['Birmingham'] timezone = city.timezone sun = city.sun(date=datetime.date.today(), local=True) if is_light_outside(sun['dawn'], sun['dusk']): logger.info("Its light outside, switching off...") switch_off() else: logger.info("Its dark outside, switching on...") switch_on()
def shut_down(): pygame.draw.rect(screen, red, (160,14,325,246),0) font5=pygame.font.Font(None,24) error = "MPC and Lights switched off" label4=font5.render(error, 1, (white)) screen.blit(label4,(160,16)) switch_off(1) error = "The system will shut down in 2 minutes" label4=font5.render(error, 1, (white)) screen.blit(label4,(160,46)) error = "Please unplug once the Pi is switched off" label4=font5.render(error, 1, (white)) screen.blit(label4,(160,66))
def put(self, lamp_id): lamp = Lamp.get(Lamp.id == lamp_id) if lamp.state == 'Off': switch_on(lamp_id) logger.info('Turned lamp on') lamp.state = 'On' lamp.save() else: switch_off(lamp_id) logger.info('Turned lamp Off') lamp.state = 'Off' lamp.save() return '', 200
def lamp(lamp, toggle): global ener_one_status global ener_two_status if lamp == 1 and toggle == 1: switch_on(1) ener_one_status = 1 elif lamp == 1 and toggle == 0: switch_off(1) ener_one_status = 0 elif lamp == 2 and toggle == 1: switch_on(2) ener_two_status = 1 elif lamp == 2 and toggle == 0: switch_off(2) ener_two_status = 0 elif lamp == 3 and toggle == 1: switch_on(1) switch_on(2) ener_one_status = 1 ener_two_status = 1 elif lamp == 3 and toggle == 0: switch_off(1) switch_off(2) ener_one_status = 0 ener_two_status = 0 return ("Ener One: " + str(ener_one_status) + ", Ener Two: " + str(ener_two_status))
def json_post(): data = request.data body = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values())) print body.PlugState print body.PlugNumber plugNum = int(body.PlugNumber) plugState = int(body.PlugState) if plugState == 1: print "inside true" switch_on(plugNum) else: print "inside false" switch_off(plugNum) return "200"
def switch(): socket = int(request.args.get('socket', '')) status = request.args.get('status', '') print("Change socket {} to {}".format(socket, status)) if status == "true": print("Switch on ", socket) switch_on(socket) else: print("Switch off ", socket) switch_off(socket) return jsonify({"socket": socket, "status": status})
def test_sound_level(self): logit("Testing sound level") self.read() volume = float(self.data["Volume"]) # Turning light on switch_on(0) f = MusicFile() f.set_volume_range(volume * 0.001, volume * 1.1) f.play(FileAlarm, 3000) time.sleep(1) f.fadeout(1000) time.sleep(2) # Turning light_off switch_off(0) loglast("Test done")
def main(): sensor = W1ThermSensor() lcd.init() while True: temp = sensor.get_temperature() print(temp) lcd.write("%s" % temp) if temp < desired_temp: switch_on() print("on") lcd.write("on", 2) else: switch_off() print("off") lcd.write("off", 2) sleep(5)
def toggle_socket(action, mysocket): # do the actual switching here... if mysocket == 'ALL': if action.upper() == "ON": logging.info("Turning ALL on...") switch_on() else: logging.info("Turning ALL off...") switch_off() else: if int(mysocket) > 0 and int(mysocket) < 5: if action.upper() == "ON": logging.info("Turning socket '" + mysocket + "' on...") switch_on(int(mysocket)) else: logging.info("Turning socket '" + mysocket + "' off...") switch_off(int(mysocket)) time.sleep(2) else: logging.debug("Skipping out of range socket.")
def main(): global INTERVAL global THINGSPEAKKEY global THINGSPEAKURL global SENSOR print 'Loading OneWire libraries into kernel... ' os.system('modprobe w1-gpio') os.system('modprobe w1-therm') print '...done.' chip_temp = 0.0 sens_temp = 0.0 print 'Entering monitor loop' print "Date\tTime\tChip\tSensor\tthingspeak response" sys.stdout.flush() try: while True: output = subprocess.check_output(['/opt/vc/bin/vcgencmd', 'measure_temp']) chip_temp = float(output[5:9]) sens_temp = read_18b20() if sens_temp >= 10.0: switch_off(1) elif sens_temp < 8.0: if os.path.isfile(LOCKFILE): print 'Temperature below 8.0 and locked off.' else: print 'Temperature below 8.0 and switching on.' switch_on(1) sys.stdout.flush() sendData(THINGSPEAKURL,THINGSPEAKKEY,chip_temp,sens_temp) sys.stdout.flush() time.sleep(INTERVAL*60) except KeyboardInterrupt: GPIO.cleanup() sys.stdout.flush()
def main(): global INTERVAL global THINGSPEAKKEY global THINGSPEAKURL global SENSOR print 'Loading OneWire libraries into kernel... ' os.system('modprobe w1-gpio') os.system('modprobe w1-therm') print '...done.' chip_temp = 0.0 sens_temp = 0.0 print 'Entering monitor loop' print "Date\tTime\tChip\tSensor\tthingspeak response" sys.stdout.flush() try: while True: output = subprocess.check_output(['/opt/vc/bin/vcgencmd', 'measure_temp']) chip_temp = float(output[5:9]) #print "Measured chip temperature {:.1f} C".format(chip_temp) sens_temp = read_18b20() #print "Measured 18b20 temperature {:.1f} C".format(sens_temp) if sens_temp > 25: switch_on(1) else: switch_off(1) #print "Sending data..." sys.stdout.flush() sendData(THINGSPEAKURL,THINGSPEAKKEY,chip_temp,sens_temp) #print "...sent." sys.stdout.flush() time.sleep(INTERVAL*60) except KeyboardInterrupt: GPIO.cleanup() sys.stdout.flush()
def button(number): if number == 13: shut_down() if number == 12: status() if number == 1: switch_on(2) if number == 2: switch_off(2) if number == 3: switch_on(1) if number == 4: switch_off(1) if number == 5: check_cam_IP()
def main(): global INTERVAL global APIKEY global TALKBACK global LOCKFILE print 'Using lockfile: ' + LOCKFILE print 'Entering command check loop' sys.stdout.flush() try: while True: # Fetch and execute the next command cmd = exec_next_command() if len(cmd) > 0: if cmd == 'ON': print 'Switching ON' os.remove(LOCKFILE) switch_on(1) elif cmd == 'OFF': print 'Switching OFF' switch_off(1) elif cmd == 'LOCKOFF': print 'Locking OFF' lock = open(LOCKFILE, 'w') lock.close() switch_off(1) else: print 'Ignoring: ' + cmd sys.stdout.flush() time.sleep(INTERVAL) except KeyboardInterrupt: print 'Interruped by user at keyboard. Halting' GPIO.cleanup() sys.stdout.flush()
def switch_off_plug(self, number = 0): if (self.__validate_plug_number(number) == True): switch_off(number)
v[1]) + cfg.UNITS[k] + ' at ' + str(v[0]) if critical_msg != '': # Turning/keeping on the ventilation if not ventilation_on: energenie.switch_on(1) ventilation_on = True try: # Sending an email (source: https://automatetheboringstuff.com/chapter16/) msg = MIMEText( critical_msg, _charset='utf-8') # Encoding the email message msg['Subject'] = Header('Air Quality Alert', 'utf-8') print('Sending email with critical values') smtpObj = smtplib.SMTP('smtp.gmail.com', 587) smtpObj.ehlo() smtpObj.starttls() smtpObj.login(cfg.EMAIL, cfg.EMAIL_PW) smtpObj.sendmail(cfg.EMAIL, cfg.EMAIL, msg.as_string()) smtpObj.quit() except smtplib.SMTPException: print('Something went wrong while sending the email') else: # Turning/keeping off the ventilation if ventilation_on: energenie.switch_off(1) ventilation_on = False except KeyboardInterrupt: print('Program stopped') sensor_on = False
#!/usr/bin/python import energenie import sys, datetime sys.stdout.write("Running sunrise-finish at %s\n" % datetime.datetime.now().isoformat()) sys.stdout.flush() energenie.switch_off(1, 2, 3)
#!/usr/bin/python import energenie import sys,datetime import time, random time.sleep(random.randrange(1200)) sys.stdout.write("Running sleep at %s\n" % datetime.datetime.now().isoformat()) sys.stdout.flush() energenie.switch_off(1) energenie.switch_off(3) time.sleep(random.randrange(1200)) energenie.switch_off(4) time.sleep(random.randrange(1200)) energenie.switch_off(2)
def message(self, msg): """ [ 1:1 CHATS. In this section we handle private (1:1) chat messages received by our bot. These may include system messages such as MUC invitations. ] """ # # Reply to help request (any message containing "powerbot" in it) # if msg['from'] != self.nick and "powerbot" in msg['body']: reply_test_message = self.make_message( mto=msg['from'].bare, mbody= "Powerbot is greeting you! Usage: [powerbot] lamp [on|off] to control socket 1, [powerbot] all [on:off] to control all sockets. Example: 'lamp on' switches socket 1 on.", mtype='chat') self.copy_dialog_id(msg, reply_test_message) reply_test_message.send() print "Sent help text: " + str(reply_test_message) # # Handle "lamp on" command # if msg['from'] != self.nick and "lamp on" in msg['body']: switch_on(lampSocket) confirmation_message = self.make_message( mto=msg['from'].bare, mbody="Lamp has been switched on.", mtype='chat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "Lamp switched on, sent confirmation: " + str( confirmation_message) # # Handle "lamp off" command # if msg['from'] != self.nick and "lamp off" in msg['body']: switch_off(lampSocket) confirmation_message = self.make_message( mto=msg['from'].bare, mbody="Lamp has been switched off.", mtype='chat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "Lamp switched off, sent confirmation: " + str( confirmation_message) # # Handle "all on" command # if msg['from'] != self.nick and "all on" in msg['body']: switch_off(lampSocket) confirmation_message = self.make_message( mto=msg['from'].bare, mbody="All sockets have been switched on", mtype='chat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "All sockets switched on, sent confirmation: " + str( confirmation_message) # # Handle "all off" command # if msg['from'] != self.nick and "all off" in msg['body']: switch_off(lampSocket) confirmation_message = self.make_message( mto=msg['from'].bare, mbody="All sockets have been switched off", mtype='chat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "All sockets switched off, sent confirmation: " + str( confirmation_message) """ MUC auto-join: Let's listen for any MUC invites and join the corresponding MUC rooms once invited. """ """if msg['mucnick'] != self.nick and "created a group" in msg['body']:""" if msg['mucnick'] != self.nick and "Create new chat" in msg['body']: from bs4 import BeautifulSoup y = BeautifulSoup(str(msg)) roomToJoin = y.xmpp_room_jid.string print("Got an invite to join room") botId = subprocess.Popen([ selfPath + " -d -j " + qbChatLogin + " -r " + str(roomToJoin) + " -n " + qbChatNick + " -p " + qbUserPass ], shell=True) print "spawned new bot ID=" print botId self.send_message( mto=msg['from'].bare, mbody= "Thank you for your kind invitation, joining your new room now!", mtype='chat')
def muc_message(self, msg): """ [ MUC CHATS. In this section we handle messages from MUC (multi-user chat rooms) our bot participates in. ] """ # # Ignore messages from offline storage, track only real time messages # delay_element = msg.xml.find('{urn:xmpp:delay}delay') if delay_element is not None: return # # Reply to help request (any message containing "powerbot" in it) # if msg['mucnick'] != self.nick and "powerbot" in msg['body']: reply_test_message = self.make_message( mto=msg['from'].bare, mbody= "Powerbot is greeting you, %s! Usage: [powerbot] lamp [on|off] to control socket 1, [powerbot] all [on:off] to control all sockets. Example: 'lamp on' switches socket 1 on." % msg['mucnick'], mtype='groupchat') self.copy_dialog_id(msg, reply_test_message) reply_test_message.send() print "Sent help text: " + str(reply_test_message) # # Handle "lamp on" command # if msg['mucnick'] != self.nick and "lamp on" in msg['body']: switch_on(lampSocket) confirmation_message = self.make_message( mto=msg['from'].bare, mbody="Lamp has been switched on, %s." % msg['mucnick'], mtype='groupchat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "Lamp switched on, sent confirmation: " + str( confirmation_message) # # Handle "lamp off" command # if msg['mucnick'] != self.nick and "lamp off" in msg['body']: switch_off(lampSocket) confirmation_message = self.make_message( mto=msg['from'].bare, mbody="Lamp has been switched off, %s." % msg['mucnick'], mtype='groupchat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "Lamp switched off, sent confirmation: " + str( confirmation_message) # # Handle "all on" command # if msg['mucnick'] != self.nick and "all on" in msg['body']: switch_off(allSockets) confirmation_message = self.make_message( mto=msg['from'].bare, mbody="All sockets have been switched on, %s." % msg['mucnick'], mtype='groupchat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "All sockets switched on, sent confirmation: " + str( confirmation_message) # # Handle "all off" command # if msg['mucnick'] != self.nick and "all off" in msg['body']: switch_off(allSockets) confirmation_message = self.make_message( mto=msg['from'].bare, mbody="All sockets have been switched off, %s." % msg['mucnick'], mtype='groupchat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "All sockets switched off, sent confirmation: " + str( confirmation_message)
def main(): global FPSCLOCK, DISPLAYSURF pygame.init() pygame.mixer.init() pygame.mixer.music.load('win-song.mp3') FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) mousex = 0 # used to store x coordinate of mouse event mousey = 0 # used to store y coordinate of mouse event pygame.display.set_caption('Memory Game') mainBoard = getRandomizedBoard() revealedBoxes = generateRevealedBoxesData(False) firstSelection = None # stores the (x, y) of the first box clicked. DISPLAYSURF.fill(BGCOLOR) startGameAnimation(mainBoard) while True: # main game loop mouseClicked = False DISPLAYSURF.fill(BGCOLOR) # drawing the window drawBoard(mainBoard, revealedBoxes) for event in pygame.event.get(): # event handling loop if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE): switch_off(0) try: pygame.mixer.music.stop() pygame.mixer.music.rewind() except: print "Tried trying try" pygame.quit() sys.exit() elif event.type == MOUSEMOTION: mousex, mousey = event.pos elif event.type == MOUSEBUTTONUP: mousex, mousey = event.pos mouseClicked = True boxx, boxy = getBoxAtPixel(mousex, mousey) if boxx != None and boxy != None: # The mouse is currently over a box. if not revealedBoxes[boxx][boxy]: drawHighlightBox(boxx, boxy) if not revealedBoxes[boxx][boxy] and mouseClicked: revealBoxesAnimation(mainBoard, [(boxx, boxy)]) revealedBoxes[boxx][boxy] = True # set the box as "revealed" if firstSelection == None: # the current box was the first box clicked firstSelection = (boxx, boxy) else: # the current box was the second box clicked # Check if there is a match between the two icons. icon1shape, icon1color = getShapeAndColor( mainBoard, firstSelection[0], firstSelection[1]) icon2shape, icon2color = getShapeAndColor( mainBoard, boxx, boxy) if icon1shape != icon2shape or icon1color != icon2color: # Icons don't match. Re-cover up both selections. pygame.time.wait(1000) # 1000 milliseconds = 1 sec coverBoxesAnimation( mainBoard, [(firstSelection[0], firstSelection[1]), (boxx, boxy)]) revealedBoxes[firstSelection[0]][ firstSelection[1]] = False revealedBoxes[boxx][boxy] = False elif hasWon(revealedBoxes): # check if all pairs found gameWonAnimation(mainBoard) pygame.time.wait(2000) # Reset the board mainBoard = getRandomizedBoard() revealedBoxes = generateRevealedBoxesData(False) # Show the fully unrevealed board for a second. drawBoard(mainBoard, revealedBoxes) pygame.display.update() pygame.time.wait(1000) # Replay the start game animation. startGameAnimation(mainBoard) switch_off(0) pygame.mixer.music.stop() firstSelection = None # reset firstSelection variable # Redraw the screen and wait a clock tick. pygame.display.update() FPSCLOCK.tick(FPS)
def fish_pump_off(): switch_off() logging.info("Switching off") s = sched.scheduler(time.time, time.sleep) s.enter(OFF_DURATION, 1, fish_pump_on, ()) s.run()
def off4(): switch_off(4) return render_template("index.html")
#!/usr/bin/python import sys import time from energenie import switch_on from energenie import switch_off switch = int(sys.argv[1]) print 'Assocating switch with number ', switch switch_on(switch) time.sleep(10) switch_off(switch) print 'Associated with number 1'
#!/usr/bin/python import sys from energenie import switch_on, switch_off if len(sys.argv) == 3: if sys.argv[1] == 'on': print "switch #"+str(int(sys.argv[2]))+" on" switch_on(int(sys.argv[2])) elif sys.argv[1] == 'off': print "switch #"+str(int(sys.argv[2]))+" off" switch_off(int(sys.argv[2])) else: print "missing argument"
from energenie import switch_on, switch_off from time import sleep switch_on(1) sleep(5) switch_off(1)
def off(self): switch_off(self.socket) self._is_on = False
def off(): for x in xrange(RETRIES): switch_off() time.sleep(0.1)
def off(): switch_off() return render_template('index.html')
from energenie import switch_on, switch_off print("Sockets 1-4 or 0 for all") while True: socket = int(raw_input('Turn socket on: ')) switch_on(socket) socket = int(raw_input("Turn socket off: ")) switch_off(socket)
def switch(socket, action): if action == 'on': energenie.switch_on(int(socket)) elif action == 'off': energenie.switch_off(int(socket)) return redirect(url_for('index'))
def toggle_lamp_off(): try: switch_off(1) return True except: return False
def turn_on_lamps(): switch_off(1)
from energenie import switch_on, switch_off from time import sleep print("Sockets 1-4 or 0 for all") while True: socket = int(raw_input('Turn socket on: ')) switch_on(socket) socket = int(raw_input("Turn socket off: ")) switch_off(socket)
def main(): global FPSCLOCK, DISPLAYSURF pygame.init() pygame.mixer.init() pygame.mixer.music.load('win-song.mp3') FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) mousex = 0 # used to store x coordinate of mouse event mousey = 0 # used to store y coordinate of mouse event pygame.display.set_caption('Memory Game') mainBoard = getRandomizedBoard() revealedBoxes = generateRevealedBoxesData(False) firstSelection = None # stores the (x, y) of the first box clicked. DISPLAYSURF.fill(BGCOLOR) startGameAnimation(mainBoard) while True: # main game loop mouseClicked = False DISPLAYSURF.fill(BGCOLOR) # drawing the window drawBoard(mainBoard, revealedBoxes) for event in pygame.event.get(): # event handling loop if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE): switch_off(0) try: pygame.mixer.music.stop() pygame.mixer.music.rewind() except: print "Tried trying try" pygame.quit() sys.exit() elif event.type == MOUSEMOTION: mousex, mousey = event.pos elif event.type == MOUSEBUTTONUP: mousex, mousey = event.pos mouseClicked = True boxx, boxy = getBoxAtPixel(mousex, mousey) if boxx != None and boxy != None: # The mouse is currently over a box. if not revealedBoxes[boxx][boxy]: drawHighlightBox(boxx, boxy) if not revealedBoxes[boxx][boxy] and mouseClicked: revealBoxesAnimation(mainBoard, [(boxx, boxy)]) revealedBoxes[boxx][boxy] = True # set the box as "revealed" if firstSelection == None: # the current box was the first box clicked firstSelection = (boxx, boxy) else: # the current box was the second box clicked # Check if there is a match between the two icons. icon1shape, icon1color = getShapeAndColor(mainBoard, firstSelection[0], firstSelection[1]) icon2shape, icon2color = getShapeAndColor(mainBoard, boxx, boxy) if icon1shape != icon2shape or icon1color != icon2color: # Icons don't match. Re-cover up both selections. pygame.time.wait(1000) # 1000 milliseconds = 1 sec coverBoxesAnimation(mainBoard, [(firstSelection[0], firstSelection[1]), (boxx, boxy)]) revealedBoxes[firstSelection[0]][firstSelection[1]] = False revealedBoxes[boxx][boxy] = False elif hasWon(revealedBoxes): # check if all pairs found gameWonAnimation(mainBoard) pygame.time.wait(2000) # Reset the board mainBoard = getRandomizedBoard() revealedBoxes = generateRevealedBoxesData(False) # Show the fully unrevealed board for a second. drawBoard(mainBoard, revealedBoxes) pygame.display.update() pygame.time.wait(1000) # Replay the start game animation. startGameAnimation(mainBoard) switch_off(0) pygame.mixer.music.stop() firstSelection = None # reset firstSelection variable # Redraw the screen and wait a clock tick. pygame.display.update() FPSCLOCK.tick(FPS)
from energenie import switch_on, switch_off from time import sleep # turn a plug socket on and off by number switch_on(1) switch_off(1) switch_on(3) switch_off(3) # turn all plug sockets on and off switch_on(0) switch_off(0) # turn some plug sockets on, then turn them off after 10 seconds switch_on(1) switch_on(4) sleep(10) switch_off(1) switch_off(4)
#Add buttons and labels make_button("Remote on", 20, 20, white) make_button("Remote off", 20, 70, white) make_button("Lights on", 20, 120, white) make_button("Lights off", 20, 170, white) make_button("Stream", 20, 220, white) make_button("Status",20, 270, white) make_button("Shutdown",20, 320, red) #While loop to manage touch screen inputs while 1: for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: pos = (pygame.mouse.get_pos() [0], pygame.mouse.get_pos() [1]) on_click() #ensure there is always a safe way to end the program if the touch screen fails if event.type == KEYDOWN: if event.key == K_ESCAPE: switch_off(1) switch_off(2) sys.exit() pygame.display.update() refresh_menu_screen() #refresh the menu interface main()
def message(self, msg): """ [ 1:1 CHATS. In this section we handle private (1:1) chat messages received by our bot. These may include system messages such as MUC invitations. ] """ # # Reply to help request (any message containing "powerbot" in it) # if msg['from'] != self.nick and "powerbot" in msg['body']: reply_test_message = self.make_message(mto=msg['from'].bare, mbody="Powerbot is greeting you! Usage: [powerbot] lamp [on|off] to control socket 1, [powerbot] all [on:off] to control all sockets. Example: 'lamp on' switches socket 1 on.", mtype='chat') self.copy_dialog_id(msg, reply_test_message) reply_test_message.send() print "Sent help text: " + str(reply_test_message) # # Handle "lamp on" command # if msg['from'] != self.nick and "lamp on" in msg['body']: switch_on(lampSocket) confirmation_message = self.make_message(mto=msg['from'].bare, mbody="Lamp has been switched on.", mtype='chat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "Lamp switched on, sent confirmation: " + str(confirmation_message) # # Handle "lamp off" command # if msg['from'] != self.nick and "lamp off" in msg['body']: switch_off(lampSocket) confirmation_message = self.make_message(mto=msg['from'].bare, mbody="Lamp has been switched off.", mtype='chat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "Lamp switched off, sent confirmation: " + str(confirmation_message) # # Handle "all on" command # if msg['from'] != self.nick and "all on" in msg['body']: switch_off(lampSocket) confirmation_message = self.make_message(mto=msg['from'].bare, mbody="All sockets have been switched on", mtype='chat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "All sockets switched on, sent confirmation: " + str(confirmation_message) # # Handle "all off" command # if msg['from'] != self.nick and "all off" in msg['body']: switch_off(lampSocket) confirmation_message = self.make_message(mto=msg['from'].bare, mbody="All sockets have been switched off", mtype='chat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "All sockets switched off, sent confirmation: " + str(confirmation_message) """ MUC auto-join: Let's listen for any MUC invites and join the corresponding MUC rooms once invited. """ """if msg['mucnick'] != self.nick and "created a group" in msg['body']:""" if msg['mucnick'] != self.nick and "Create new chat" in msg['body']: from bs4 import BeautifulSoup y = BeautifulSoup(str(msg)) roomToJoin = y.xmpp_room_jid.string print ("Got an invite to join room") botId = subprocess.Popen([selfPath + " -d -j " + qbChatLogin + " -r " + str(roomToJoin) + " -n " + qbChatNick + " -p " + qbUserPass], shell=True) print "spawned new bot ID=" print botId self.send_message(mto=msg['from'].bare, mbody="Thank you for your kind invitation, joining your new room now!", mtype='chat')
async def start_bottle_warmer(self, msg, timeout=4.5 * 60): e.switch_on(1) await self.sender.sendMessage("Started bottle warmer.") await asyncio.sleep(timeout) e.switch_off(1) await self.sender.sendMessage("Stopped bottle warmer.")
def button(number): if number == 13: shut_down() if number == 12: status() if number == 1: switch_on(2) if number == 2: switch_off(2) if number == 3: switch_on(1) if number == 4: switch_off(1) if number == 5: check_cam_IP() if number == 6: subprocess.call("mpc play ", shell=True) if number == 7: subprocess.call("mpc stop ", shell=True) if number == 8: subprocess.call("mpc volume -2 ", shell=True) if number == 9: subprocess.call("mpc volume +2 ", shell=True) if number == 10: subprocess.call("mpc prev ", shell=True) if number == 11: subprocess.call("mpc next ", shell=True) if number == 14: pygame.draw.rect(screen, black, (160,14,325,246),0) weather() pygame.draw.rect(screen, yellow, (163,290, 420, 40),0) station_font=pygame.font.Font(None,20) title_font=pygame.font.Font(None,34) station = subprocess.check_output("mpc current", shell=True ) station=str(station) print (station) lines=station.split(":") print (lines) length = len(lines) if length==1: line1 = lines[0] line2 = "No additional info: " else: line1 = lines[0] line2 = lines[1] line1 = line1.replace("b'", "") line1 = line1[:45] line2 = line2[:45] line2 = line2[:-3] print ("line1") print (line1) print ("line2") print (line2) #trap no station data if line1 =="'": line1 = "No Station information available" line2 = "Press PLAY or REFRESH" station_status = "stopped" status_font = red else: station_status = "playing" status_font = green station_name=station_font.render(line1, 1, (red)) additional_data=station_font.render(line2, 1, (blue)) station_label=title_font.render(station_status, 1, (status_font)) screen.blit(station_label,(166,290)) screen.blit(station_name,(270,295)) screen.blit(additional_data,(270,315)) pygame.draw.rect(screen, cream, (504,225, 120, 30),0) ## check to see if the Radio is connected to the internet font=pygame.font.Font(None,22) IP = subprocess.check_output("hostname -I", shell=True ) IP = str(IP) print (IP) if "10" in IP: network_status = "online" status_font = green else: network_status = "offline" status_font = red network_status_label = font.render(network_status, 1, (status_font)) screen.blit(network_status_label, (505,230)) volume = subprocess.check_output("mpc volume", shell=True ) volume = volume[8:] volume = volume[:-1] if volume == "00%": volume = "max" volume_tag=font.render(volume, 1, (black)) screen.blit(volume_tag,(560,230)) pygame.display.flip()
from energenie import switch_on, switch_off from time import sleep while True: print("switching on...") switch_on() sleep(2) print("switching off...") switch_off() sleep(2)
#!/usr/bin/python import energenie energenie.switch_off() energenie.cleanup()
def muc_message(self, msg): """ [ MUC CHATS. In this section we handle messages from MUC (multi-user chat rooms) our bot participates in. ] """ # # Ignore messages from offline storage, track only real time messages # delay_element = msg.xml.find('{urn:xmpp:delay}delay') if delay_element is not None: return # # Reply to help request (any message containing "powerbot" in it) # if msg['mucnick'] != self.nick and "powerbot" in msg['body']: reply_test_message = self.make_message(mto=msg['from'].bare, mbody="Powerbot is greeting you, %s! Usage: [powerbot] lamp [on|off] to control socket 1, [powerbot] all [on:off] to control all sockets. Example: 'lamp on' switches socket 1 on." % msg['mucnick'], mtype='groupchat') self.copy_dialog_id(msg, reply_test_message) reply_test_message.send() print "Sent help text: " + str(reply_test_message) # # Handle "lamp on" command # if msg['mucnick'] != self.nick and "lamp on" in msg['body']: switch_on(lampSocket) confirmation_message = self.make_message(mto=msg['from'].bare, mbody="Lamp has been switched on, %s." % msg['mucnick'], mtype='groupchat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "Lamp switched on, sent confirmation: " + str(confirmation_message) # # Handle "lamp off" command # if msg['mucnick'] != self.nick and "lamp off" in msg['body']: switch_off(lampSocket) confirmation_message = self.make_message(mto=msg['from'].bare, mbody="Lamp has been switched off, %s." % msg['mucnick'], mtype='groupchat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "Lamp switched off, sent confirmation: " + str(confirmation_message) # # Handle "all on" command # if msg['mucnick'] != self.nick and "all on" in msg['body']: switch_off(allSockets) confirmation_message = self.make_message(mto=msg['from'].bare, mbody="All sockets have been switched on, %s." % msg['mucnick'], mtype='groupchat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "All sockets switched on, sent confirmation: " + str(confirmation_message) # # Handle "all off" command # if msg['mucnick'] != self.nick and "all off" in msg['body']: switch_off(allSockets) confirmation_message = self.make_message(mto=msg['from'].bare, mbody="All sockets have been switched off, %s." % msg['mucnick'], mtype='groupchat') self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "All sockets switched off, sent confirmation: " + str(confirmation_message)
def switch_socket(self, state): if state == 'on': switch_on(self.socket_id) if state == 'off': switch_off(self.socket_id)
#!/usr/bin/env python #-------------------------------------- # # Script to switch ON or OFF the Energenie sockets through PiMote # add-on board for the Raspberry Pi. This is using Energenie Python # module. On Raspberry Pi, install the energenie module in pip (Python 3) # # sudo apt-get install python3-pip # sudo pip-3.2 install energenie # #-------------------------------------- # Import modules import energenie as e import time import sys # Get command line arguments socketID = int(sys.argv[1]) action = sys.argv[2] if (socketID > 4 or socketID < 1 or (action != 'on' and action != 'off')): exit("Invalid arguments") if (sys.argv[2] == 'on'): e.switch_on(socketID) elif (sys.argv[2] == 'off'): e.switch_off(socketID)