def switchon(): socket = int(request.query.socket) if (socket >= 0 and socket <= 4) : #print 'Switching on {}'.format(socket) switch_on (socket) if (socket == 0) : return 'Requested switch on ALL' else : return 'Requested switch on {}'.format(socket)
def switchon(): socket = int(request.query.socket) if (socket >= 0 and socket <= 4): #print 'Switching on {}'.format(socket) switch_on(socket) if (socket == 0): return 'Requested switch on ALL' else: return 'Requested switch on {}'.format(socket)
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 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(): switch_on(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 on') return
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 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 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 now(self): logit("Launching alarm") volume = float(self.data["Volume"]) print("Volume is ", 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(10) f.fadeout(1000) time.sleep(2) loglast("Done")
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 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 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 gameWonAnimation(board): # flash the background color when the player has won switch_on(0) sleep(0.5) pygame.mixer.music.play() coveredBoxes = generateRevealedBoxesData(True) color1 = LIGHTBGCOLOR color2 = BGCOLOR for i in range(13): color1, color2 = color2, color1 # swap colors DISPLAYSURF.fill(color1) drawBoard(board, coveredBoxes) pygame.display.update() pygame.time.wait(300)
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 on(): switch_on() return render_template('index.html')
def switch_on_plug(self, number = 0): if (self.__validate_plug_number(number) == True): switch_on(number)
#!/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)
(crit_time, crit_value) = find_crit_val(timestamps, ppm_vals[gas], cfg.UPPERBOUNDS[gas]) crit_dict[gas] = (crit_time, crit_value) critical_msg = '' for k, v in crit_dict.items(): # If we find a critical value, we add this to critical_msg if v[0] is not None and v[1] is not None: critical_msg += '\nCritical value for ' + k + ' of ' + str( 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()
def on3(): switch_on(3) return render_template("index.html")
def turn_on_lamps_once(): switch_on(1) return schedule.CancelJob
#!/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'
def on1(): switch_on(1) 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)
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)
from energenie import switch_on, switch_off from time import sleep # turn all plug sockets on and off switch_on() switch_off() # turn a plug socket on and off by number switch_on(1) switch_off(1) switch_on(2) switch_off(2)
def toggle_lamp_on(): try: switch_on(1) return True except: return False
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 fish_pump_on(): switch_on() logging.info("Switching on") s = sched.scheduler(time.time, time.sleep) s.enter(ON_DURATION, 1, fish_pump_off, ()) s.run()
def on2(): switch_on(2) return render_template("index.html")
def on(): for x in xrange(RETRIES): switch_on() time.sleep(0.1)
def on4(): switch_on(4) return render_template("index.html")
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)
def on(self): switch_on(self.socket) self._is_on = True
#!/usr/bin/python import cgitb cgitb.enable() import energenie energenie.switch_on() 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)
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)
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 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.")
from energenie import switch_on, switch_off from time import sleep switch_on(0) switch_on(1) switch_on(2) switch_on(3) #switch_off(0) #switch_off(1) #switch_off(2) #switch_off(3)
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 really_switch_on(tries=5, *sockets): print "Switching on %s at %s" % (",".join([str(s) for s in sockets]),datetime.datetime.now().isoformat()) for x in range(tries): energenie.switch_on(*sockets) time.sleep(1)
#!/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)