def valveJob(setting): #(valve, onDuration) print 'OPENING VALVE' tft.markActiveJob(setting['id'], True); durationLeft = int(setting['on_duration']) + 2 #binaryValveList = map(int, list(format(setting['valve'], '08b'))) #print binaryValveList pump = Relay() pump.on() time.sleep(1) #valves = Shiftregister() #shiftreg.outputList(binaryValveList) valves.outputDecimal(setting['valve']) #valves.enable() while durationLeft > 2: time.sleep(1) durationLeft -= 1 print 'TIME LEFT: %i' % (durationLeft - 1) print 'CLOSING VALVE' pump.off() print 'reset shift register 1' #valves.disable() valves.reset() time.sleep(1) #valves.reset() tft.markActiveJob(setting['id'], False); db = DB() db.addLogLine(setting, datetime.now()) return
async def test_async(): relay = Relay(2) relay.on() print("on") asyncio.sleep(1) relay.off() print("off") asyncio.sleep(1) asyncio.create_task(relay.async_blink()) for i in range(0,10): print(i) if i == 5: relay.stop_async_blink() await asyncio.sleep(1)
class Humidifier(): """A Humidifier class.""" def __init__(self, power_pin, button_pin, name, status=0): self.power_relay = Relay(power_pin, name + '_power_relay', 0) self.button = Button(button_pin, name + '_button', 0) self.status = 0 # self.nominal_status = 0 # 0 = Off - 1 = On - 2 = on for - 3 = pulse self.advanced_status = 0 # active, pause time. It is valid only if self.status = 1 self.status_interval = [] # Interval used to activate the component after a certain time self.interval = None def get_status(self): # convert to boolean return not(not self.advanced_status) def set_status(self, status): if status == 0: self.power_relay.off() else: self.power_relay.on() self.button.switch_status() def on(self): # if self.status <> 1: self.set_status(1) self.status = 1 self.advanced_status = 1 def on_for(self, active_time): logging.debug('Humidifier on_for: %s', active_time) self.on() time.sleep(active_time) self.off() self.advanced_status = 1 def pulse(self, active_time, sleep): set_interval(on_for) def off(self): self.set_status(0) self.status = 0 self.advanced_status = 0
def demo(): from relay import Relay import time relay = Relay(2) relay.off() data = b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" frc = Mfrc522() print("Checking Tag") print(frc.read()) relay.on() time.sleep(1) relay.flip() relay.blink() print("Writting data to tag") print(frc.write(data)) relay.stop_blink() time.sleep(1) relay.on() print("Check again") print(frc.read()) time.sleep(1) relay.off()
class RunLoop: SLEEP_MS_DEFAULT = 20 LED_TOGGLE_DEFAULT = 500 def __init__(self, config, verbose=0): self.verbose = verbose # ------------------------------------------------------------------------------------------------------------ # self.exit = False self.config = config # ------------------------------------------------------------------------------------------------------------ # self.sleep_ms = self.SLEEP_MS_DEFAULT # ------------------------------------------------------------------------------------------------------------ # # Initialise required services # ------------------------------------------------------------------------------------------------------------ # if self.config['pinout']['led'] is None: from led import MockLed self.led = MockLed() else: from led import Led self.led = Led(self.config['pinout']['led']['pin'], self.config['pinout']['led']['on_level']) # ------------------------------------------------------------------------------------------------------------ # if self.config['pinout']['button'] is None: from button import MockButton self.button = MockButton() else: from button import Button self.button = Button(self.config['pinout']['button']['pin'], self.config['pinout']['button']['on_level']) # ------------------------------------------------------------------------------------------------------------ # if self.config['pinout']['relay'] is None: from relay import MockRelay self.relay = MockRelay() else: from relay import Relay self.relay = Relay(self.config['pinout']['relay']['pin'], self.config['pinout']['relay']['on_level']) # ------------------------------------------------------------------------------------------------------------ # self.wifi = WiFi(self.config) # , verbose=self.verbose) self.device_id = self.wifi.device_id() self.messaging = Messaging(self.config, self.device_id) # ------------------------------------------------------------------------------------------------------------ # # Application ready feedback --------------------------------------------------------------------------------- # self.led.on(poll=True) sleep(2) self.led.off(poll=True) # ------------------------------------------------------------------------------------------------------------ # if self.wifi.connected(): self.on_wifi_connected(be_verbose=False) # ------------------------------------------------------------------------------------------------------------ # if self.verbose: print('<{} with id {}>'.format(self.config['device']['type'], self.device_id)) print(self.led) print(self.button) print(self.relay) print(self.wifi) print(self.messaging) def on_wifi_connected(self, be_verbose=True): if be_verbose and self.verbose: print(self.wifi) self.led.toggle(self.LED_TOGGLE_DEFAULT) if not self.messaging.connected(): self.messaging.connect() def run(self): if self.verbose: print('Run loop ' 'started') while not self.exit: # ======================================================================================================== # self.led.poll() self.button.poll() # -------------------------------------------------------------------------------------------------------- # if self.relay.state( ) == self.relay.STATE_OFF and self.button.pressed( ) == self.button.SHORT_PRESS: if self.verbose: print('<Button: SHORT_PRESS ' '0' '>') self.messaging.publish({ 'state': '<Button: SHORT_PRESS ' 'relay state: ' 'on' '>' }) self.relay.on() self.button.clear() elif self.relay.state( ) == self.relay.STATE_ON and self.button.pressed( ) > self.button.NOT_PRESSED: if self.verbose: print('<Button: SHORT_PRESS ' '1' '>') self.messaging.publish({ 'state': '<Button: SHORT_PRESS ' 'relay state: ' 'off' '>' }) self.relay.off() self.button.clear() elif self.led.enabled() is True and self.button.pressed( ) == self.button.LONG_PRESS: if self.verbose: print('<Button: LONG_PRESS ' '0' '>') self.messaging.publish({ 'state': '<Button: LONG_PRESS ' 'led enabled: ' 'off' '>' }) self.led.enable(False) self.led.off() self.button.clear() elif self.led.enabled() is False and self.button.pressed( ) > self.button.NOT_PRESSED: if self.verbose: print('<Button: LONG_PRESS ' '2' '>') self.messaging.publish( {'state': '<Button: LONG_PRESS ' 'led enabled: ' 'on' '>'}) self.led.enable(True) self.led.toggle(self.LED_TOGGLE_DEFAULT) self.button.clear() # -------------------------------------------------------------------------------------------------------- # if self.wifi.connected(): if self.messaging.connected() is False: self.on_wifi_connected() if self.messaging.poll(): if 'action' in self.messaging.msg: if self.messaging.msg['action'] == 'on': if self.verbose: print('<Relay: ' 'on' '>') self.relay.on() elif self.messaging.msg['action'] == 'off': if self.verbose: print('<Relay: ' 'off' '>') self.relay.off() elif self.messaging.msg['action'] == 'exit': if self.verbose: print('<Application: ' 'exit' '>') self.exit = True self.messaging.completed() elif self.wifi.connected() is False: if self.wifi.connecting() is False: self.led.toggle(250) self.led.on(poll=True, save_state=True) if self.wifi.connect() is True: self.led.off(poll=True, restore_state=True) # ======================================================================================================== # sleep_ms(self.sleep_ms) # Reduce the tightness of the run loop # ======================================================================================================== # if self.verbose: print('Run loop ' 'exited') def close(self): self.exit = True if self.led: self.led.close() if self.button: self.button.close() if self.relay: self.relay.close() if self.messaging: self.messaging.disconnect() # if self.wifi: # self.wifi.disconnect() # Don't do this, you will loose connection to the REPL if self.verbose: print('Run loop ' 'closed')
from flask import Flask, request, jsonify from relay import Relay from time import sleep from gpiozero import LED app = Flask(__name__) provider = Relay(2) provider.off() @app.route("/") def root(): return "hello world" @app.route("/transfer") def transfer(): energy = int(request.args['energy']) provider.on() sleep(energy) provider.off() return "did something" if __name__ == '__main__': app.run(host='0.0.0.0')
class Poller(): def __init__(self, settings_path): self.settings_path = settings_path # load settings self.settings = settings_handler.load_settings(settings_path) # arrange paths self.program_path = self.settings['paths']['program'] self.examples_path = self.settings['paths']['examples'] self.daily_log_path = self.settings['paths']['daily_log'] # get intervals self.thermometer_poll = self.settings['poll_intervals']['temperature'] self.time_to_wait = self.settings['poll_intervals']['settings'] # parameters for UDP communication with thermometer self.UDP_IP = self.settings['configs']['UDP_IP'] self.UDP_port = self.settings['configs']['UDP_port'] self.thermometer = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.thermometer.settimeout(1) self.thermometer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.temperature = self.settings['temperatures']['room'] # handle day change if (self.settings['log']['last_day_on'] != util.get_now()['formatted_date']): self.time_elapsed = 0 util.write_log( self.daily_log_path, { 'date': self.settings['log']['last_day_on'], 'time_elapsed': util.format_seconds(self.time_elapsed) }) self.time_elapsed = 0 else: time_elapsed_restore = datetime.datetime.strptime( self.settings['log'].get('time_elapsed', '0:00:00'), '%H:%M:%S') self.time_elapsed = round( datetime.timedelta( hours=time_elapsed_restore.hour, minutes=time_elapsed_restore.minute, seconds=time_elapsed_restore.second).total_seconds()) self.program_number = self.settings['mode']['program'] relay_settings = self.settings['relay'] self.heater_switch = Relay(relay_settings, self.settings_path) self.last_current = None self.loop_count = 0 self.count_start = time.perf_counter() def poll(self, current): ''' Poll the settings.json file and behaves accordingly: - First sends a request for room temperature if self.loop_count is 0 or a multiple of self.thermometer_poll (from settings file) - If room temperature is lower than desired_temp: - First checks if manual is ON - Then checks for auto mode Returns self.time_to_wait when heater is turned ON, 0 when OFF ''' self.count_start = time.perf_counter() self.settings = settings_handler.handler( settings_path=self.settings_path, settings_changes={ 'log': { 'time_elapsed': util.format_seconds(self.time_elapsed), 'last_day_on': current['formatted_date'] } }) logger.debug('Settings handler in poller: {}'.format(self.settings)) manual = self.settings['mode']['manual'] auto = self.settings['mode']['auto'] desired_temperature = self.settings['mode']['desired_temp'] logger.debug('time to wait: {}'.format(self.time_to_wait)) return self._handle_on_and_off(current, **self.settings['mode']) def _handle_on_and_off(self, current, manual, auto, program, desired_temp): ''' Handles all there is to turning the heater on or off: modes, programs, temperature. ''' # Get room temperature self.temperature = self.request_temperatures() # MANUAL MODE if manual: return self._manual_mode(desired_temp) # AUTO MODE elif auto: return self._auto_mode(desired_temp, current) # BOTH MANUAL AND AUTO ARE OFF else: return self.turn_off() def _manual_mode(self, desired_temperature): ''' Action to take when MANUAL mode is True Manual mode prevails over auto mode and so does desired_temperature over possible numbers in program.json ''' # Room temperature is lower than desired temperature if self.temperature < desired_temperature: return self.turn_on() # Room temperature satisfies desired temperature else: return self.turn_off() def _auto_mode(self, desired_temperature, current): ''' Action to take when AUTO mode is True ''' # Load program p = self._load_program(current) # Load program setting at current day and time program_now = p.program[current['weekday']][str(current['hours'])] logger.debug('Program is now: {}'.format(program_now)) ### TURN ON CASE if ( # Value in program is bool, True, and room temp is # lower than desired temperature (program_now is True and self.temperature < desired_temperature) or (util.is_number(program_now) and self.temperature < program_now)): return self.turn_on() ### TURN OFF CASE elif ( # Value in program is bool, True and room temp is # greater than desired temperature (program_now is True and self.temperature >= desired_temperature) or (util.is_number(program_now) and self.temperature >= program_now)): return self.turn_off() ### ANYTHING ELSE GOES TO OFF, JUST IN CASE else: return self.turn_off() def _load_program(self, current): program = Program(program_number=self.program_number, program_path=self.program_path, examples_path=self.examples_path) logger.debug('Loaded program {}.'.format(program.program_number)) logger.debug("It is {} on {}.".format(current['formatted_time'], current['weekday'].title())) return program def turn_on(self): seconds = self.time_to_wait # only when heater was off at previous loop if not self.heater_switch.stats: # set seconds to 60 so it doesn't immediately turn back off # when temperatures are fluctuating seconds = 60 # reset loop_count so it will read temperatures # right away on next loop self.loop_count = -1 logger.info('Room temperature lower than set desired temperature!' ' Turning ON heater.') logger.debug('Heater switch stats: {}'.format( self.heater_switch.stats)) logger.debug('Received signal to turn heater ON.') # start it self.heater_switch.on() self.heater_switch.catch_sleep(seconds, self.temperature) return time.perf_counter() - self.count_start def turn_off(self): seconds = self.time_to_wait # only when heater was on at previous loop if self.heater_switch.stats: # set seconds to 170 so it doesn't immediately turn back on # when temperatures are fluctuating seconds = 170 # reset loop_count so it will read temperatures # right away on next loop self.loop_count = -1 logger.info('Reached desired temperature.' ' Turning OFF heater and waiting' ' {} seconds before next poll.'.format(seconds)) logger.debug('Received signal to turn heater OFF.') # stop it self.heater_switch.off() self.heater_switch.catch_sleep(seconds, self.temperature) return 0 def request_temperatures(self): ''' Send a request for temperatures to ESP8266. Response should be a JSON of the type: { "celsius": float } If request goes into timeout: request is skipped, self.temperature is set to None, request is repeated on next loop. If request is succesful and new temperature is different than what's reported in settings.json file: update the file and self.temperature. ''' logger.debug('Loop count: {}; thermometer poll: {}; read: {}.'.format( self.loop_count, self.thermometer_poll, not self.loop_count % self.thermometer_poll)) if not self.loop_count or not self.loop_count % self.thermometer_poll: self.thermometer.sendto(b'temps_req', (self.UDP_IP, self.UDP_port)) try: self.temperature = json.loads( self.thermometer.recv(4096).decode())['celsius'] self.loop_count = 0 except socket.timeout: self.loop_count = -1 if self.temperature != self.settings['temperatures']['room']: self.settings = settings_handler.handler( settings_path=self.settings_path, settings_changes={ 'temperatures': { 'room': self.temperature } }) logger.debug('Temperature from thermometer is: {}° celsius.'.format( self.temperature)) return self.temperature
class Controller: def __init__(self, positionRepository): self.isAdjusting = False self.directionRelay = Relay(constants.PIN_DIRECTION_RELAY, "Directory Relay") self.powerRelay = Relay(constants.PIN_POWER_RELAY, "Power Relay") self.positionRepository = positionRepository def adjust(self, targetPosition, client): currentPosition = self.positionRepository.read() if self.isAdjusting: return # Would be better to throw an error i suppose else: self.isAdjusting = True shouldOpen = self.__should_open(currentPosition, targetPosition) if (shouldOpen == False): self.directionRelay.on() duration = self.__calculate_movement_duration(currentPosition, targetPosition) curPos = 0.0 + currentPosition self.powerRelay.on() while True: # if we reached 0, quit the job. if not, push notif if duration <= 0: break else: if client != None: client.adjustment_callback(round(curPos)) # Determine a proper amount to sleep toSleep = 0.5 if (duration < 0.5): toSleep = duration # wait to keep that relay high time.sleep(toSleep) # calculate remaining duration duration = duration - toSleep # calculate the new current position if (shouldOpen): curPos = curPos + ( 100.0 / (constants.SHUTTING_DURATION_IN_SECONDS / 0.5)) else: curPos = curPos - ( 100.0 / (constants.SHUTTING_DURATION_IN_SECONDS / 0.5)) # Turn all relays off self.powerRelay.off() self.directionRelay.off() # make sure the position repo has the last state print('writing new position {0}'.format(targetPosition)) self.positionRepository.write(targetPosition) # invoke callback for the interested parties client.adjustment_callback(targetPosition) self.isAdjusting = False def currentPosition(self): return self.positionRepository.read() def __calculate_movement_duration(self, currentPosition, targetPosition): percentualDifference = abs(currentPosition - targetPosition) secondByPercent = (constants.SHUTTING_DURATION_IN_SECONDS / 100.0) return percentualDifference * secondByPercent def __should_open(self, currentPosition, targetPosition): return currentPosition < targetPosition
class Wifi(ConfigOp): def __init__(self, hostname, pin=2): self.__wlan = None self.__timeout = DEFAULT_TMOUT self.__led = Relay(pin) self.is_ok = False self.gw = None self.ip = None self.dns = None ConfigOp.__init__(self, 'wifi', CONFIG_NAME) self.add_command(self.__get_info, GET) self.add_command(self.__reconnect, SET, 'reconnect') self.__hostname = hostname def is_connected(self): return self.__wlan != None and self.__wlan.isconnected() async def __get_info(self, _): v = self.get_info() await sleep(0) return result(200, None, v) async def __reconnect(self, _): delayed_task(5000, self.async_connect, (True), True) return result(200, None, RECONNECT_WIFI) async def __reload_config(self): # NOSONAR return await self.__reconnect(None) def get_info(self): return { "mac": MAC, "connected": self.is_connected(), "connection tested": self.is_ok, "hostname": self.__hostname, "ip": self.ip, "gw": self.gw, "dns": self.dns } def check_wifi_config(self): self.load() return not (self.__config is None or is_str_empty(self.__config[SSID]) or is_str_empty(self.__config[PASSWORD])) def disconnect(self): if self.__wlan is not None and self.__wlan.isconnected(): self.__wlan.disconnect() self.__wlan.active(False) async def async_connect(self, force_rec=False): if self.__wlan is not None and self.__wlan.isconnected(): if force_rec: self.disconnect() return await self.__async_connect() return True return await self.__async_connect() async def __async_connect(self): self.__connect_init() return await self.__async_connect_finish() async def __async_connect_finish(self): start_time = time() # Check time while not self.__wlan.isconnected(): await sleep_ms(DEFAULT_300) self.__led.on() await sleep_ms(DEFAULT_300) self.__led.off() if time() - start_time > self.__timeout: log.error("Wifi connection timeout: %d", self.__timeout) break return self.__set_properties() def __connect_init(self): self.check_wifi_config() if self.__config is None: log.error("Wifi config is None") return log.info("Connect to wifi: %s", self.__config[SSID]) self.__wlan = WLAN(STA_IF) # 创建 station 接口 if self.__wlan.isconnected(): self.__wlan.disconnect() self.__wlan.active(True) # Activate the interface self.__wlan.scan() # Scan self.__led.off() self.__wlan.config(dhcp_hostname=self.__hostname) self.__wlan.connect(self.__config[SSID], self.__config[PASSWORD]) # 连接到指定ESSID网络 if TIMEOUT in self.__config: self.__timeout = self.__config[TIMEOUT] def __set_properties(self): if self.__wlan.isconnected(): log.info('network information: %r', self.__wlan.ifconfig()) (self.ip, _, self.gw, self.dns) = self.__wlan.ifconfig() self.is_ok = True self.__led.on() else: self.ip = None self.gw = None self.dns = None self.is_ok = False self.__wlan = None self.__led.off() return self.is_ok def check_connection(self): if hw.WIFI_CHECK_TYPE == 0: return True if not self.is_connected(): return False if hw.WIFI_CHECK_TYPE == 1: return True dest = self.gw if hw.WIFI_CHECK_TYPE == 3: if WIFI_CHECK_HOST in self.__config != None: dest = self.__config[WIFI_CHECK_HOST] else: dest = hw.WIFI_CHECK_HOST return ping_check(dest) async def monitor(self): log.debug("Setup wifi monitor") while hw.WIFI: try: await sleep(hw.WIFI_CHECK_INTVAL) if not self.check_connection(): log.info("Wifi is not ready, reconnecting...") await self.async_connect(True) except: #NOSONAR # pylint: disable=W0702 pass