Beispiel #1
0
    def set_description(self, description):
        if (description == self.get_description()):
            return False

        self.__cache['description'] = description
        from relays import Relays
        Relays.write_config()
Beispiel #2
0
    def set_notes(self, notes):
        if (notes == self.get_notes()):
            return False

        self.__cache['notes'] = notes
        from relays import Relays
        Relays.write_config()
Beispiel #3
0
    def set_name(self, name):
        if (name == self.get_name()):
            return False

        self.__cache['name'] = name
        from relays import Relays
        Relays.write_config()
Beispiel #4
0
    def set_initValue(self, initValue):
        if (initValue == self.get_initValue()):
            return False

        self.__cache['initValue'] = initValue
        from relays import Relays
        Relays.write_config()
def api_add_relay():
    relayStr = request.form['data']
    print(relayStr)

    relay = Relays.add(relayStr)
    socketio.emit('updated_relays_status', Relays.get_relays_raw())
    return make_response(relay.to_JSON(), 200)
Beispiel #6
0
def init():
	gc.enable()
	Status.init()
	if not Config.init():
		Config.factoryReset()
	Config.init()
	Wifi.init()
	Leds.init()
	Sensors.init()
	Relays.init()
	if Config.getParam("time", "ntp"):
		i = 1
		try:
			while i < 5 and not ntpclient.settime(Config.getParam("time", "ntp"), Config.getParam("time", "offset")):
				Status.log("Getting time from NTP... (%s)" % i)
				i += 1
			rtc = machine.RTC()
			t = rtc.datetime()
		except Exception:
			t = utime.localtime(0)
	else:
		t = utime.localtime(0)
	Status.log('Date: {:04d}.{:02d}.{:02d} {:02d}:{:02d}:{:02d}'.format(t[0], t[1], t[2], t[4], t[5], t[6]))
	# Init timer
	tim = machine.Timer(0)
	tim.init(period=50, mode=machine.Timer.PERIODIC, callback=tick50mS())
Beispiel #7
0
    def set_inverted(self, inverted):
        if (inverted == self.get_inverted()):
            return False

        self.__cache['inverted'] = inverted
        self.set_status(self.get_status_HW())
        from relays import Relays
        Relays.write_config()
def api_get_name(relay_id):
    if not Relays.is_valid_relayId(relay_id):
        return make_response(get_message("Invalid ID: " + str(relay_id)), 404)
    relay = Relays.get_relay(relay_id)
    if request.method == 'POST':
        print(request.form['data'])
        relay.set_name(json.loads(request.form['data']))
    return make_response(json.dumps(relay.get_name()), 200)
def api_get_status(relay_id):
    if not Relays.is_valid_relayId(relay_id):
        return make_response(get_message("Invalid ID: " + str(relay_id)), 404)
    status = Relays.get_relay(relay_id).get_status()
    if status:
        return make_response("1", 200)
    else:
        return make_response("0", 200)
def api_get_initValue(relay_id):
    if not Relays.is_valid_relayId(relay_id):
        return make_response(get_message("Invalid ID: " + str(relay_id)), 404)
    relay = Relays.get_relay(relay_id)
    if request.method == 'POST':
        print(request.form['data'])
        relay.set_initValue(json.loads(request.form['data']))
        socketio.emit('updated_relays_status', Relays.get_relays_raw())
    return make_response(json.dumps(relay.get_initValue()), 200)
Beispiel #11
0
  def __init__(self):

    self.motionDetected = False;
    self.relay = Relays(7);
    self.relay.setAllOff();
    self.motion = Motion(0, 3, self);
    self.light = Light(3, 1000, self);
    self.temp = Temp(1, 85, self);

    self.start = time.time();

    while True:
      print('********** Switch Module Starting **********');
      time.sleep(5);
Beispiel #12
0
    def set_status(self, status):
        print('Setting relay status', self.__cache['name'], '->', status)
        self.__cache['status'] = status

        if (self.get_status_HW() == status):
            print('Unchanged status for', self.__cache['name'], '- keeping', status)
            return False

        if self.__cache['inverted']:
            statusHW = not status
        else:
            statusHW = status
        self.__type.set(statusHW)
        print('Set HW Status for',self.__cache['name'], '->', statusHW)
        from relays import Relays
        Relays.write_config()
Beispiel #13
0
def iothub_client_sample_run():
    try:
        global client, sensor, relays, logger, remoteRelay, MESSAGE_COUNT
        client = iothub_client_init()

        logger = Logging()
        sensor = ReadData()
        relays = Relays()
        remoteRelay = RemoteRelay()

        if client.protocol == IoTHubTransportProvider.MQTT:
            print("IoTHubClient is reporting state")
            #reported_state = "{\"newState\":\"standBy\",\"relaysState\":{\"dining\":\"off\"}}"
            #client.send_reported_state(reported_state, len(reported_state), send_reported_state_callback, SEND_REPORTED_STATE_CONTEXT)
            reportState(relays)
        message = composeStartMessage()
        client.send_event_async(message, send_confirmation_callback,
                                MESSAGE_COUNT)
        print(
            "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub."
            % MESSAGE_COUNT)

        status = client.get_send_status()
        print("Send status: %s" % status)
        MESSAGE_COUNT += 1

        #telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_SUCCESS, "IoT hub connection is established")
        while True:
            global MESSAGE_SWITCH
            if MESSAGE_SWITCH:
                # send a few messages every minute
                print("IoTHubClient sending %d messages" % MESSAGE_COUNT)

                message = composeMessage(sensor, relays)
                client.send_event_async(message, send_confirmation_callback,
                                        MESSAGE_COUNT)
                print(
                    "IoTHubClient.send_event_async accepted message [%d] for transmission to IoT Hub."
                    % MESSAGE_COUNT)

                status = client.get_send_status()
                print("Send status: %s" % status)
                MESSAGE_COUNT += 1

            #log current state
            statusText = readDeviceData(sensor, relays, remoteRelay, logger)

            if AUTO_CONTROL:
                autoControl()
            time.sleep(config.MESSAGE_TIMESPAN / 1000.0)

    except IoTHubError as iothub_error:
        print("Unexpected error %s from IoTHub" % iothub_error)
        #telemetry.send_telemetry_data(parse_iot_hub_name(), EVENT_FAILED, "Unexpected error %s from IoTHub" % iothub_error)
        return
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped")

    print_last_message_time(client)
Beispiel #14
0
def test():
    print()
    print("#################################")
    print("TEST: get_relay_byIndex")
    relay = Relays.get_relay_byIndex(0)

    print()
    print("#################################")
    print("TEST: Relay status")
    relay.get_status_HW()

    print()
    print("#################################")
    print("TEST: Relay ON")
    relay.on()

    print()
    print("#################################")
    print("TEST: Relay OFF")
    relay.off()

    print()
    print("#################################")
    print("TEST: Relay TOGGLE")
    relay.toggle()

    print()
    print("#################################")
    print("TEST: Relay all ON")
    Relays.on()

    print()
    print("#################################")
    print("TEST: Relay all OFF")
    Relays.off()

    print()
    print("#################################")
    print("TEST: Relay all TOGGLE")
    Relays.toggle()

    print()
    print("#################################")
    print("TEST: Check invalid index")
    try:
        Relays.get_relay_byIndex(200)
        raise ValueError("Invalid index not detected")
    except ValueError:
        pass  #Expected
Beispiel #15
0
config.CONFIG['output_root'] defined in config.py

Default output directory: ./www
'''

import os
import sys
from shutil import copytree
import config
from relays import Relays

ABS_PATH = os.path.dirname(os.path.abspath(__file__))

if __name__ == '__main__':
    try:
        RELAY_SET = Relays()
    except Exception as err:
        print(
            'error creating relays object from onionoo response, aborting...')
        print(err)
        sys.exit()

    # generate relay HTML documents
    RELAY_SET.create_output_dir()
    RELAY_SET.write_unsorted('index.html', is_index=True)
    RELAY_SET.write_unsorted('all.html', is_index=False)
    RELAY_SET.write_effective_family()
    RELAY_SET.write_pages_by_key('as')
    RELAY_SET.write_pages_by_key('country')
    RELAY_SET.write_pages_by_key('platform')
    RELAY_SET.write_pages_by_flag()
Beispiel #16
0
 def info(numRelay):
     print(Relays.state(numRelay))
def api_delete_relay(relay_id):
    if not Relays.is_valid_relayId(relay_id):
        return make_response(get_message("Invalid ID: " + str(relay_id)), 404)
    Relays.delete(relay_id)
    socketio.emit('updated_relays_status', Relays.get_relays_raw())
    return make_response("", 200)
Beispiel #18
0
 def run(self, numRelays):
     Relays.switch(numRelays, self.mode, self.seconds)
     return 1
def api_all_relay_toggle():
    Relays.toggle()
    socketio.emit('updated_relays_status', Relays.get_relays_raw())
    return make_response(get_message("ALL Toggled OK"), 200)
def api_all_relay_off():
    Relays.off()
    socketio.emit('updated_relays_status', Relays.get_relays_raw())
    return make_response(get_message("ALL Turned ON OK"), 200)
def api_relay_all_status():
    status = Relays.get_relays_raw()
    return make_response(json.dumps(status), 200)
def api_relay_off(relay_id):
    if not Relays.is_valid_relayId(relay_id):
        return make_response(get_message("Invalid ID: " + str(relay_id)), 404)
    Relays.get_relay_byId(relay_id).off()
    socketio.emit('updated_relays_status', Relays.get_relays_raw())
    return make_response(get_message("Turned OFF OK"), 200)
Beispiel #23
0
 def info(numRelay):
     print(Relays.state(numRelay))
Beispiel #24
0
class Switch:

  def __init__(self):

    self.motionDetected = False;
    self.relay = Relays(7);
    self.relay.setAllOff();
    self.motion = Motion(0, 3, self);
    self.light = Light(3, 1000, self);
    self.temp = Temp(1, 85, self);

    self.start = time.time();

    while True:
      print('********** Switch Module Starting **********');
      time.sleep(5);

  def motionOn(self):
    self.motionDetected = True;
    self.relay.set(0, 1);

  def motionOff(self):
    self.motionDetected = False;
    self.relay.set(0, 0);

  def tempOn(self):
    self.relay.set(1, 1);

  def tempOff(self):
    self.relay.set(1, 0);

  def lightOn(self):
    if self.motionDetected and self.relay.read(0) == 0:
      self.relay.set(0, 1);

  def lightOff(self):
    if not self.motionDetected and self.relay.read(0) == 1:
      self.relay.set(0, 0);
Beispiel #25
0
from relays import Relays
import tracker
import os
import json
import logging

logger = logging.getLogger('State')

relays = Relays()
rooms = {}
tmpHold = False
settings = {}
weather = {}

# First, load defaults (or newly added settings
try:
    with open('settings.default.json') as df:
        settings = json.load(df)
except:
    logger.error('Could not load default settings file!')

# Now try and load settings from a saved settings file
try:
    with open('settings.json') as f:
        settings = {**settings, **json.load(f)}
        logger.info('Loaded settings from file:')
        logger.info(settings)
except:
    logger.warning('Settings file not found. Using default file!')

# Set the current avgTmp to the current setTmp