Exemplo n.º 1
0
def main():

    if len(sys.argv) != 3:
        usage()
        sys.exit(1)

    command = sys.argv[1]

    if command not in ("on", "off"):
        usage()
        sys.exit(1)

    device_number = sys.argv[2]

    if device_number not in ("1", "2", "3", "4"):
        usage()
        sys.exit(1)

    device_number = int(device_number)

    if command == "on":
        device = Energenie(device_number, True)
        # lamp.on() # Above just does the job
    else:
        device = Energenie(device_number, False)
Exemplo n.º 2
0
def check_humid():
    if humidity > MAX_HUMID:
        print("Turning off humid")
        Energenie(1, initial_value=False)
    if humidity < MIN_HUMID:
        print("Turning on humid")
        Energenie(1, initial_value=True)
Exemplo n.º 3
0
    def do_GET(self):

        try:
            if self.path != '/off' and self.path != '/on':
                return SimpleHTTPRequestHandler.do_GET(self)

            # The second Energenie parameter is carefully selected here to avoid
            # toggling the state unnecessarily
            if self.path == '/on':
                device = Energenie(ENERGENIE_DEVICE, True)
                # device.on()
            else:
                device = Energenie(ENERGENIE_DEVICE, False)
                # device.off()

            self.send_response(200)
            self.send_header("Content-type", "text/plain")
            self.end_headers()

            self.wfile.write(b'OK')

            # Do not close in Python3, it is done automatically
            # self.wfile.close()

        except Exception:
            print(('do_GET(): Caught exception:', sys.exc_info()[0]))
            traceback.print_exc()
Exemplo n.º 4
0
def fruiting_humid():
    global humid_count
    if humid_count % 120 == 0:
        print("Turning on humid")
        Energenie(1, initial_value=True)
    elif humid_count % 120 == 2:
        print("Turning off humid")
        Energenie(1, initial_value=False)
    humid_count = humid_count + 1
def check_temp():
    global temp_on
    if temperature > MAX_TEMP:
        print("Turning off temp")
        temp_on = False
        Energenie(2, initial_value=False)
    if temperature < MIN_TEMP:
        print("Turning on temp")
        temp_on = True
        Energenie(2, initial_value=True)
Exemplo n.º 6
0
    def __init__(self, socket):
        super(EnergenieOutput, self).__init__()
        self.socket = socket
        self.state = 'OFF'
        # set the pins numbering mode
        GPIO.setmode(GPIO.BCM)

        # Select the GPIO pins used for the encoder D0-D3 data inputs
        GPIO.setup(17, GPIO.OUT, initial=GPIO.LOW)
        GPIO.setup(22, GPIO.OUT, initial=GPIO.LOW)
        GPIO.setup(23, GPIO.OUT, initial=GPIO.LOW)
        GPIO.setup(27, GPIO.OUT, initial=GPIO.LOW)
        # Select GPIO used to select ASK/FSK (default ASK)
        GPIO.setup(24, GPIO.OUT, initial=GPIO.LOW)
        # Select GPIO used to enable/disable modulator (default disabled)
        GPIO.setup(25, GPIO.OUT, initial=GPIO.LOW)
        self.energenie = Energenie(socket)
Exemplo n.º 7
0
 def master_callback(self, hermes, intent_message):
     if intent_message.intent.intent_name == 'pezholio:energenie_all_on':
         for i in range(1, 4):
             lamp = Energenie(i)
             lamp.on()
             lamp.on()
     elif intent_message.intent.intent_name == 'pezholio:energenie_all_off':
         for i in range(1, 4):
             lamp = Energenie(i)
             lamp.off()
             lamp.off()
Exemplo n.º 8
0
class EnergenieOutput(object):
    """
    Use energenie as an output for brumulus.
    """
    def __init__(self, socket):
        super(EnergenieOutput, self).__init__()
        self.socket = socket
        self.state = 'OFF'
        # set the pins numbering mode
        GPIO.setmode(GPIO.BCM)

        # Select the GPIO pins used for the encoder D0-D3 data inputs
        GPIO.setup(17, GPIO.OUT, initial=GPIO.LOW)
        GPIO.setup(22, GPIO.OUT, initial=GPIO.LOW)
        GPIO.setup(23, GPIO.OUT, initial=GPIO.LOW)
        GPIO.setup(27, GPIO.OUT, initial=GPIO.LOW)
        # Select GPIO used to select ASK/FSK (default ASK)
        GPIO.setup(24, GPIO.OUT, initial=GPIO.LOW)
        # Select GPIO used to enable/disable modulator (default disabled)
        GPIO.setup(25, GPIO.OUT, initial=GPIO.LOW)
        self.energenie = Energenie(socket)

    def is_state(self, state):
        if self.state == state:
            return True
        return False

    def set_state(self, state):
        if state == 'ON':
            self.energenie.on()
            self.state = 'ON'
            return 'ON'
        if state == 'OFF':
            self.energenie.off()
            self.state = 'OFF'
            return 'OFF'

        raise Exception('Cannot set EnergenieOutput state to {}'.format(state))

    def get_state(self):
        return self.state
Exemplo n.º 9
0
class EnergenieOutput(object):
    """
    Use energenie as an output for brumulus.
    """
    def __init__(self, socket):
        super(EnergenieOutput, self).__init__()
        self.socket = socket
        self.state = 'OFF'
        self.energenie = Energenie(socket)

    def is_state(self, state):
        if self.state == state:
            return True
        return False

    def set_state(self, state):
        if state == 'ON':
            self.energenie.on()
            return 'ON'
        if state == 'OFF':
            self.energenie.off()
            return 'OFF'

        raise Exception('Cannot set EnergenieOutput state to {}'.format(state))
Exemplo n.º 10
0
class terrariumPowerSwitchEnergenieRF(terrariumPowerSwitchSource):
    TYPE = 'eg-pm-rf'

    def load_hardware(self):
        self.__device = Energenie(int(self.get_address()))

    def set_hardware_state(self, state, force=False):
        if state:
            self.__device.on()
        else:
            self.__device.off()

    def stop(self):
        self.__device.close()
Exemplo n.º 11
0
def reset_router():

    """
    Reset home router using energenie sockets and raspberry pi
    """

    # Define router as socket 2 - I have 2 sockets installed
    router = Energenie(2)
    
    # Turn off router
    router.off()
    print('Reset router, now wait 30 seconds before turning back on')
    # Wait to allow router to reset
    time.sleep(30)
    # Turn router back on
    router.on()
Exemplo n.º 12
0
#!/usr/bin/python3

# lights-off.py - For Terrarium Controllers using Adafruit
# DHT sensors, Energenie Pimote sockets, and ThingSpeak.
# MIT license.
# http://bennet.org/blog/raspberry-pi-terrarium-controller/

# Imports
from gpiozero import Energenie

# Main lights off
lightsocket = 2
l = Energenie(lightsocket, initial_value=False)
Exemplo n.º 13
0
 def __init__(self):
     self.state = 'empty'
     self.ready = True
     system('ssh zero ./lock &')
     mixer.init()
     self.light = Energenie(1)
Exemplo n.º 14
0
class Room:
    """
        Convert gesture actions detected into responses, such as playing music and turning lights
        on. This class is hard-coded for the demo video. It will not work without modification as
        you probably don't have a machine called 'zero' with lock and unlock scripts, or the file
        audio/epic.mp3, which was used under licence.

        To explore your own neural network's behaviour, see run.py instead. Otherwise use this as
        a template to build your own gesture-driven automation.
    """
    def __init__(self):
        self.state = 'empty'
        self.ready = True
        system('ssh zero ./lock &')
        mixer.init()
        self.light = Energenie(1)

    def update(self, action):
        if action == NONE:
            self.ready = True

        if not self.ready:
            return

        if action != NONE:
            self.ready = False

        if action == DOOR:
            if self.state == 'empty':
                self.enter()
                self.state = 'occupied'
            elif self.state == 'occupied':
                self.leave()
                self.state = 'empty'
        elif action == LIGHT:
            self.toggle_light()
        elif action == MUSIC:
            self.play_music()
        elif action == STOP:
            self.dim_music()

    def enter(self):
        stderr.write('\nEnter\n')
        self.light.on()
        mixer.music.load('audio/good-evening.wav')
        mixer.music.set_volume(1.0)
        mixer.music.play()
        system('ssh zero ./unlock &')

    def toggle_light(self):
        if self.light.value:
            stderr.write('\nLight off\n')
            self.light.off()
        else:
            stderr.write('\nLight on\n')
            self.light.on()

    def play_music(self):
        stderr.write('\nMusic play\n')
        mixer.music.load('audio/epic.mp3')
        mixer.music.set_volume(0.5)
        mixer.music.play()

    def dim_music(self):
        stderr.write('\nDim music\n')
        mixer.music.set_volume(0.1)

    def leave(self):
        stderr.write('\nLeave\n')
        mixer.music.fadeout(1)
        mixer.music.load('audio/good-night.wav')
        mixer.music.set_volume(1.0)
        mixer.music.play()
        self.light.off()
        system('ssh zero ./lock &')
        sleep(5)
        mixer.music.load('audio/alarm-active.wav')
        mixer.music.play()
Exemplo n.º 15
0
# If either reading has failed after repeated retries,
# abort and log message to ThingSpeak
thingspeak_key = 'XXXXXXXXXXXXXXXX'
if humidity is None or temperature is None:
    f = requests.post('https://api.thingspeak.com/update.json',
                      data={
                          'api_key': thingspeak_key,
                          'status': 'failed to get reading'
                      })

# Otherwise, check if temperature is above threshold,
# and if so, activate Energenie socket for cooling fan
else:
    fansocket = 1
    tempthreshold = 28

    if temperature > tempthreshold:
        # Activate cooling fans
        f = Energenie(fansocket, initial_value=True)

    else:
        # Deactivate cooling fans
        f = Energenie(fansocket, initial_value=False)

    # Send the data to Thingspeak
    r = requests.post('https://api.thingspeak.com/update.json',
                      data={
                          'api_key': thingspeak_key,
                          'field1': temperature,
                          'field2': humidity
                      })
Exemplo n.º 16
0
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software.  If not, see <http://www.gnu.org/licenses/>

from gpiozero import Energenie
import bottle
from bottle import route, request, response, template, static_file

sockets = [None]
sockets.append(Energenie(1))
sockets.append(Energenie(2))
sockets.append(Energenie(3))
sockets.append(Energenie(4))

# allow on all ip addresses
HOST = ''
# port 80 - standard web port (assumes no other web server installed)
# If using apache or another browser then change this to a different value
PORT = 80

# Folder where this is installed and the index.html file is located
# The index.html file is exposed to the webserver as well as any files in a subdirectory called public (ie. /home/pi/pi-power/public)
DOCUMENT_ROOT = '/home/pi/pi-power'

# Create the bottle web server
Exemplo n.º 17
0
def create_pump():
    from gpiozero import Energenie
    pump_socket = Energenie(ENERGENIE_PUMP_SOCKET_NUMBER)
    return pump_socket
Exemplo n.º 18
0
def switch_on_pump():
    from gpiozero import Energenie
    pump_socket = Energenie(ENERGENIE_PUMP_SOCKET_NUMBER)
    pump_socket.on()

    logging.debug("Pump On")
Exemplo n.º 19
0
def off():
    with Energenie(1) as heater:
        heater.off()
Exemplo n.º 20
0
def on():
    with Energenie(1) as heater:
        heater.on()
class PlugDriver(Seizer):

	def __init__(self):
		interestedIdentifiers = ["LightsCommand"]
		super(PlugDriver,self).__init__()
		self.configureSeizer(interestedIdentifiers,True)
		self.livingRoomLights = Energenie(1)
		self.bedRoomLights = Energenie(2)

	def handleLightsCommand(self, header):
		if header == "allOn":
			self.allOn()
                elif header == "bedRoomOn": 
                        self.bedRoomLights.on() 
                elif header == "livingRoomOn":
                        self.livingRoomLights.on()
		elif header == "allOff":
			self.allOff()
		elif header == "bedRoomOff":
			self.bedRoomLights.off()
                elif header == "livingRoomOff": 
                        self.livingRoomLights.off()
		else:
			print "Unrecognised command: " + header + "."

	def allOff(self):
		self.livingRoomLights.off()
		self.bedRoomLights.off()

	def allOn(self):
		self.livingRoomLights.on()
		self.bedRoomLights.on()

	def run(self):
		while True:
			[header, payload] = self.seize()
			if header == "LightsCommand":
				self.handleLightsCommand(payload)
			else:
				print "Unrecognised header"
	def __init__(self):
		interestedIdentifiers = ["LightsCommand"]
		super(PlugDriver,self).__init__()
		self.configureSeizer(interestedIdentifiers,True)
		self.livingRoomLights = Energenie(1)
		self.bedRoomLights = Energenie(2)
Exemplo n.º 23
0
# Set Document Root by using the current file directory
DOCUMENT_ROOT = os.path.dirname(os.path.abspath(__file__))

# Load JSON config
with open(DOCUMENT_ROOT + '/config.json', 'r') as f:
    CONFIG = json.load(f)

# print(json.dumps(CONFIG, indent=4, sort_keys=True))

# Dynamically load the sockets we're controlling
sockets = [0]
for key, val in CONFIG['sockets'].items():
    # Convert the key from a string to an integer
    key = int(key)
    # Create our connection to the socket and set the default state of the socket
    sockets.insert(key, Energenie(key, bool(val['default_state'])))


# Function to control the socket
def energenie_socket_power(id, action):
    # Open a connection to the socket
    socket = sockets[id]

    # Do action
    if action == 'off':
        socket.off()
    elif action == 'on':
        socket.on()

    # Sleep, to ensure the command is sent
    sleep(0.05)
Exemplo n.º 24
0
def power_off():
    now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    print("Turning off cooker at {}".format(now))
    Energenie(PORT, initial_value=False)
Exemplo n.º 25
0
from gpiozero import Energenie, TimeOfDay
from datetime import time
from signal import pause

lamp = Energenie(1)
daytime = TimeOfDay(time(8), time(20))

lamp.source = daytime.values
lamp.source_delay = 60

pause()
Exemplo n.º 26
0
from gpiozero import Energenie, TimeOfDay
from datetime import time
from signal import pause

lamp = Energenie(1)
daytime = TimeOfDay(time(8), time(20))

lamp.source = daytime
lamp.source_delay = 60

pause()
Exemplo n.º 27
0
def device_and_settings_loop():

    # Don't share db connection between threads.
    db = sqlite3.connect(dirname + 'vivarium_ctrl.db')
    c = db.cursor()

    # Initialise devices.
    heat_mat = Energenie(constants.HEAT_MAT_SOCKET)
    pump = Energenie(constants.PUMP_SOCKET)
    fan = Energenie(constants.FAN_SOCKET)
    light = Energenie(constants.LIGHT_SOCKET)

    logger.info('Device and settings thread started.')

    # Continue running until interrupted.
    while not running.is_set():

        #  Update device states.
        device_states = c.execute('SELECT * FROM device_states')
        for device_state in device_states:
            if device_state[0] == 'heat-mat':
                if to_bool(device_state[1]) != heat_mat.value:
                    heat_mat.value = to_bool(device_state[1])
            elif device_state[0] == 'pump':
                if to_bool(device_state[1]) != pump.value:
                    pump.value = to_bool(device_state[1])
            elif device_state[0] == 'fan':
                if to_bool(device_state[1]) != fan.value:
                    fan.value = to_bool(device_state[1])
            elif device_state[0] == 'light':
                if to_bool(device_state[1]) != light.value:
                    light.value = to_bool(device_state[1])

        # Check if settings need reloading.
        reload_settings = to_bool(
            c.execute("SELECT state FROM flags WHERE flag='reload_settings'").
            fetchone()[0])
        if reload_settings:
            load_settings()
            c.execute(
                "UPDATE flags SET state = 0 WHERE flag = 'reload_settings'")
            db.commit()

        # Pause briefly.
        running.wait(constants.DEVICE_AND_SETTINGS_INTERVAL)

    # Close db and switch off all devices.
    db.close()
    heat_mat.off()
    pump.off()
    fan.off()
    light.off()
    logger.info(
        'Device and settings thread stopped. All devices have been turned off.'
    )
Exemplo n.º 28
0
def switch_off_boiler():
    from gpiozero import Energenie
    boiler_socket = Energenie(ENERGENIE_BOILER_SOCKET_NUMBER)
    boiler_socket.off()

    logging.debug("Boiler Off")
Exemplo n.º 29
0
def off():
    with Energenie(3) as device:
        device.off()
Exemplo n.º 30
0
def on():
    with Energenie(3) as device:
        device.on()
Exemplo n.º 31
0
from gpiozero import Energenie, TimeOfDay
from datetime import time
from signal import pause

lamp = Energenie(1)
daytime = TimeOfDay(time(8), time(20))

daytime.when_activated = lamp.on
daytime.when_deactivated = lamp.off

pause()
Exemplo n.º 32
0
 def load_hardware(self):
   self.__device = Energenie(int(self.get_address()))
Exemplo n.º 33
0
 def __init__(self, socket):
     super(EnergenieOutput, self).__init__()
     self.socket = socket
     self.state = 'OFF'
     self.energenie = Energenie(socket)