Exemplo n.º 1
0
def awake():
    """
    Sends WakeOnLAN packet to the MAC addresses in MACS.
    Also, turns on TV'sock (SHARP IP control).

    """
    # send wol packet to the machines
    for mac in MACS:
        iterator = iter(mac)
        mac_s = ':'.join(a + b for a, b in zip(iterator, iterator))
        wol.send_magic_packet(mac_s, broadcast='192.168.1.255')
    # turn on the tvs, switch to hdmi1
    for televisio in TVS:
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect(televisio)
            sock.sendall(TV_COMMANDS['powr1'])
            sock.recv(9)
            sock.sendall(TV_COMMANDS['hdmi1'])
            sock.recv(9)
            sock.sendall(TV_COMMANDS['hdmi1'])
            sock.recv(9)
            sock.close()
        except Exception:
            pass
Exemplo n.º 2
0
	def wake_nodes(self):
		if running_on_linux()==True:
			if get_distro=="Fedora":
				print "waking all nodes:"
				for i in range(0, len(self.nodes)):
					print "waking", self.nodes[i].mac
					wol.send_magic_packet(self.nodes[i].mac)
Exemplo n.º 3
0
def awake():
    """
    Sends WakeOnLAN packet to the MAC addresses in MACS.
    Also, turns on TV'sock (SHARP IP control).

    """
    # send wol packet to the machines
    for mac in MACS:
        iterator = iter(mac)
        mac_s = ':'.join(a + b for a, b in zip(iterator, iterator))
        wol.send_magic_packet(mac_s, broadcast='192.168.1.255')
    # turn on the tvs, switch to hdmi1
    for televisio in TVS:
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect(televisio)
            sock.sendall(TV_COMMANDS['powr1'])
            sock.recv(9)
            sock.sendall(TV_COMMANDS['hdmi1'])
            sock.recv(9)
            sock.sendall(TV_COMMANDS['hdmi1'])
            sock.recv(9)
            sock.close()
        except Exception:
            pass
Exemplo n.º 4
0
    def wol(self, mac):
        """
		Wake-on-lan (wol)
		in: hw addr
		out: None
		"""
        wol.send_magic_packet(mac)
Exemplo n.º 5
0
   def handle_command(self,command):

      commands = self.get_commands()
      response = []    
      
      try:
         tempActions = (item["actions"] for item in commands if item["name"].lower() == command.lower()).next()

         for action in tempActions:   
            #print("----------")
            #print(action)
            #print("----------")
            
            #Stereo
            if (action.get('type') == 'serial'):
               response = controllers().write_to_serial_port(action.get('data'),action.get('location'))
               time.sleep(float(action.get('delay')))               
            #Volume control
            if (action.get('type') == 'volume'):
               zone = action.get('data').split(',')[0]
               volume = int(self.get_volume(zone,action.get('location')))
               if action.get('data').split(',')[1] == "up":
                  volume += 5
               else:
                  volume -= 5
               data = "&AH66,VOL," + zone + "," + str(volume)
               controllers().write_to_serial_port(data,action.get('location'))
               location = self.zone_name(zone,action.get('location'))
               response.append('volume,' + location + ',' + str(volume))
            if (action.get('type') == 'source'):
               zone = action.get('data').split(',')[0]
               source = action.get('data').split(',')[1]
               data = "&AH66,AUD," + zone + "," + source
               controllers().write_to_serial_port(data,action.get('location'))
               location = self.zone_name(zone,action.get('location'))
               source = self.source_name(source)
               if (location != None):
                   response.append('source,' + location + ',' + source)
            #Wake Computer
            if (action.get('type') == 'wake'):
               wol.send_magic_packet(action.get('data'))
            #IR transmission
            if (action.get('type') == 'ir'):
               controllers().write_to_ir(action.get('data'),action.get('location'))
               time.sleep(float(action.get('delay')))
            #Press keys on computer
            if (action.get('type') == 'key press'):
               controllers().write_to_computer(action.get('data'))
            #Run another command
            if (action.get('type') == 'command'):
               results = self.handle_command(action.get('data'), status)
               #print ('sending keypress from type = command')
                 
      except:
         print("Error occurred in requestprocessor handle_command.")
         print(sys.exc_info()[0])

      return response
Exemplo n.º 6
0
   def handle_command(self,command):

      commands = self.get_commands()
      response = []    
      
      try:
         tempActions = (item["actions"] for item in commands if item["name"].lower() == command.lower()).next()

         for action in tempActions:   
            #print("----------")
            #print(action)
            #print("----------")
            
            #Stereo
            if (action.get('type') == 'serial'):
               response = controllers().write_to_serial_port(action.get('data'),action.get('location'))
               time.sleep(float(action.get('delay')))               
            #Volume control
            if (action.get('type') == 'volume'):
               zone = action.get('data').split(',')[0]
               volume = int(self.get_volume(zone,action.get('location')))
               if action.get('data').split(',')[1] == "up":
                  volume += 5
               else:
                  volume -= 5
               data = "&AH66,VOL," + zone + "," + str(volume)
               controllers().write_to_serial_port(data,action.get('location'))
               location = self.zone_name(zone,action.get('location'))
               response.append('volume,' + location + ',' + str(volume))
            if (action.get('type') == 'source'):
               zone = action.get('data').split(',')[0]
               source = action.get('data').split(',')[1]
               data = "&AH66,AUD," + zone + "," + source
               controllers().write_to_serial_port(data,action.get('location'))
               location = self.zone_name(zone,action.get('location'))
               source = self.source_name(source)
               response.append('source,' + location + ',' + source)
            #Wake Computer
            if (action.get('type') == 'wake'):
               wol.send_magic_packet(action.get('data'))
            #IR transmission
            if (action.get('type') == 'ir'):
               controllers().write_to_ir(action.get('data'),action.get('location'))
               time.sleep(float(action.get('delay')))
            #Press keys on computer
            if (action.get('type') == 'key press'):
               controllers().write_to_computer(action.get('data'))
            #Run another command
            if (action.get('type') == 'command'):
               results = self.handle_command(action.get('data'), status)
               #print ('sending keypress from type = command')
                 
      except:
         print("Error occurred in requestprocessor handle_command.")
         print(sys.exc_info()[0])

      return response
Exemplo n.º 7
0
 def test_invalid_broadcast(self):
     for bc in INVALID_BROADCASTS:
         try:
             wol.send_magic_packet('11:11:11:11:11:11', bc)
         except ValueError:
             e = utils.fetch_last_exception()
             self.assertIn('Invalid broadcast', e.args[0])
         else:
             emsg = "The broadcast '%s' should not pass the test! " % bc
             raise AssertionError(emsg)
Exemplo n.º 8
0
	def wakeAllComputers(self):
		all = self.db.getAll()
		
		if all.count() == 0:
			self.log.info('[*] Database empty')
			return
		
		self.log.info('[*] Waking known computers:')
		for h in all:
			mac = h['mac']
			wol.send_magic_packet(mac)
			self.log.info('  > %s / %s'%(mac,h['ip']))
		self.log.info('----------------------------')
Exemplo n.º 9
0
    def wakeAllComputers(self):
        all = self.db.getAll()

        if all.count() == 0:
            self.log.info("[*] Database empty")
            return

        self.log.info("[*] Waking known computers:")
        for h in all:
            mac = h["mac"]
            wol.send_magic_packet(mac)
            self.log.info("  > %s / %s" % (mac, h["ip"]))
        self.log.info("----------------------------")
Exemplo n.º 10
0
def WOL(mac, ip, name):
    #Send Magic packet to wakeup iPhone
    for iteration in range(10):
        wol.send_magic_packet(mac, dest=ip, port=9)
        time.sleep(.1)
    #Check to see if iPhone is online
    time.sleep(2)
    response = 1
    attempts = 0
    #Try 3 times to ping it
    while response != 0 and attempts < 3:
        response = os.system("ping -c 1 " + ip + " > /dev/null")
        attempts = attempts + 1
    if response == 0:
        #print "Online"
        pingstatus = "Online"
    else:
        #print "Offline"
        pingstatus = "Offline"
    return pingstatus
Exemplo n.º 11
0
utility_q_url = os.environ['UTILITY_Q_URL']

while True:
    response = sqs.receive_message(
        QueueUrl=utility_q_url,
        MaxNumberOfMessages=10,
        MessageAttributeNames=[
            'All'
        ],
        WaitTimeSeconds=5
    )
    messages_to_delete = []
    if 'Messages' in response:
        for message in response['Messages']:
            body = json.loads(message['Body'])
            print('Received message with body: {}'.format(body))
            if body['target'] != 'RaspberryPi':
                print('Not intended for this system, ignoring...')
                continue
            else:
                print('Intended for this system, processing...')
            if body['intent'] == 'SmartHomeAction' and body['action'] == 'TurnOn' and body['entity'] == 'Battlestation':
                print("Turning on Battlestation...")
                wol.send_magic_packet(battlestation_mac_address)
                messages_to_delete.append({'Id': message['MessageId'], 'ReceiptHandle': message['ReceiptHandle']})
    if messages_to_delete:
        sqs.delete_message_batch(
            QueueUrl=utility_q_url,
            Entries=messages_to_delete
        )
Exemplo n.º 12
0
def wake_cosmo():
    wol.send_magic_packet('D8:CB:8A:39:E2:BF')
    return jsonify({"action": "woke cosmo"})
Exemplo n.º 13
0
def handle(text, mic, profile):
    """
        Broadcast a magic packet to wake up the computer and send a signal to the
        Arduino to tell it which OS to pick from

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone number)
    """

    text = text.lower()
    ## Try to work out which OS to wake up
    match = re.search(r"(?P<action>\w+) (?P<target>\w+)", text)
    if match:
        ## tempted to just use "os" here but it is a package name, meh
        target = match.group("target")
        action = match.group("action")
        os_config = profile["activator"]
        if target not in os_config:
            if target != "check" and target != "tunnel":
                #target not recognised
                mic.say("I'm sorry. Target operating system %s is not recognised." % target)
                return # break
        if action == "activate":
            try:
                if target == "check":
                    ser = serial.Serial("/dev/ttyUSB0", 38400, timeout=2)
                    write(ser, "check")
                    mic.say("Activation checking!")
                elif target == "tunnel":
                    ser = serial.Serial("/dev/ttyUSB0", 38400, timeout=2)
                    write(ser, "tunnel")
                    mic.say("Activating tunnel")
                    rnd_suffix = str(randint(1000,9999))
                    subprocess.Popen(["node", "/usr/local/bin/lt", "--port", "80", "--subdomain", "famanson%s" % rnd_suffix, "&"])
                    mic.say("Your suffix is %s" % rnd_suffix)
                else:
                    mic.say("Activating %s." % target)
                    mac = os_config[target]["mac"]
                    dest = None
                    if "host" in os_config[target]:
                        dest = os_config[target]["host"]
                    wol.send_magic_packet(mac, dest=dest)

                    # Now sleep for 20 seconds to wait for grub to show up
                    time.sleep(20)
                    ser = serial.Serial("/dev/ttyUSB0", 38400, timeout=2)

                    # Send the activate command
                    write(ser, target)
                    ack1 = read(ser)
                    if not ack1 or ACK1 not in ack1:
                        print ack1
                        mic.say("Acknowledge signal 1 was not received")
                        raise ValueError
                    # Got ack2
                    mic.say("Activation completed!")
            except:
                traceback.print_exc()
                mic.say("Error found. Activation failed!")
            finally:
                if ser:
                    print "Closing Serial connection"
                    ser.close()

        elif action == "close":
            mic.say("Closing %s." % target)
            if target == "windows":
                return
            else:
                host = os_config[target]["host"]
                subprocess.Popen(["ssh", "pi@%s" % host, "sudo", "poweroff"])
    else:
        mic.say("I'm sorry I did not catch your last command. Please try again.")
Exemplo n.º 14
0
	def wol(self, mac):
		wol.send_magic_packet(mac)
Exemplo n.º 15
0
 def wakeTranscoder():
     wol.send_magic_packet(C.transcoderMac)
Exemplo n.º 16
0
import os
from awake import wol

mac = ''
broadcast_addr = ''
ip_addr_file = './configuration/sony_bravia.conf'

if os.path.isfile(ip_addr_file):
    with open(ip_addr_file, 'r') as fo:
        for line in fo:
            if line.startswith('MAC:'):
                mac = line.strip('MAC: ')
                mac = mac.strip('\n')
            if line.startswith('BA:'):
                broadcast_addr = line.strip('BA: ')
                broadcast_addr = broadcast_addr.strip('\n')
        wol.send_magic_packet(mac, broadcast_addr, port=9)
Exemplo n.º 17
0
def handle(text, mic, profile):
    """
        Broadcast a magic packet to wake up the computer and send a signal to the
        Arduino to tell it which OS to pick from

        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone number)
    """

    text = text.lower()
    ## Try to work out which OS to wake up
    match = re.search(r"(?P<action>\w+) (?P<target>\w+)", text)
    if match:
        ## tempted to just use "os" here but it is a package name, meh
        target = match.group("target")
        action = match.group("action")
        os_config = profile["activator"]
        if target not in os_config:
            if target != "check" and target != "tunnel":
                #target not recognised
                mic.say(
                    "I'm sorry. Target operating system %s is not recognised."
                    % target)
                return  # break
        if action == "activate":
            try:
                if target == "check":
                    ser = serial.Serial("/dev/ttyUSB0", 38400, timeout=2)
                    write(ser, "check")
                    mic.say("Activation checking!")
                elif target == "tunnel":
                    ser = serial.Serial("/dev/ttyUSB0", 38400, timeout=2)
                    write(ser, "tunnel")
                    mic.say("Activating tunnel")
                    rnd_suffix = str(randint(1000, 9999))
                    subprocess.Popen([
                        "node", "/usr/local/bin/lt", "--port", "80",
                        "--subdomain",
                        "famanson%s" % rnd_suffix, "&"
                    ])
                    mic.say("Your suffix is %s" % rnd_suffix)
                else:
                    mic.say("Activating %s." % target)
                    mac = os_config[target]["mac"]
                    dest = None
                    if "host" in os_config[target]:
                        dest = os_config[target]["host"]
                    wol.send_magic_packet(mac, dest=dest)

                    # Now sleep for 20 seconds to wait for grub to show up
                    time.sleep(20)
                    ser = serial.Serial("/dev/ttyUSB0", 38400, timeout=2)

                    # Send the activate command
                    write(ser, target)
                    ack1 = read(ser)
                    if not ack1 or ACK1 not in ack1:
                        print ack1
                        mic.say("Acknowledge signal 1 was not received")
                        raise ValueError
                    # Got ack2
                    mic.say("Activation completed!")
            except:
                traceback.print_exc()
                mic.say("Error found. Activation failed!")
            finally:
                if ser:
                    print "Closing Serial connection"
                    ser.close()

        elif action == "close":
            mic.say("Closing %s." % target)
            if target == "windows":
                return
            else:
                host = os_config[target]["host"]
                subprocess.Popen(["ssh", "pi@%s" % host, "sudo", "poweroff"])
    else:
        mic.say(
            "I'm sorry I did not catch your last command. Please try again.")