示例#1
0
 def __init__(self):
     info('receiver', 'init')
     self.queue = Queue()
     self.mqtt = MQTT(os.environ['KIT_CHANNEL'],
                      client_id='receiver-mqtt',
                      queue=self.queue)
     self.running = False
示例#2
0
 def run(self):
     self.api.registerController()
     for bot, config in self.config.get('bots').items():
         self.bots[bot] = Bot(bot, config, self.keysDB)
         r = self.api.subscribeBot(**self.bots[bot].credentials)
         log.debug("subscription response code = '{}".format(r))
     self.mqtt = MQTT(self.broker, name=self.name, botController=self)
示例#3
0
    def _init_mqtt(self):
        self._mqtt_client = MQTT(secrets.mqtt_broker, secrets.mqtt_port,
                                 secrets.mqtt_user, secrets.mqtt_pass,
                                 self.logger)
        self._mqtt_client.start()

        while self._mqtt_client.connected != True:
            time.sleep(0.1)

        self._mqtt_client.send_message("buttons", "Running")
        self._mqtt_client.send_message("lights/lounge", "update")
        self._mqtt_client.on_command = self.handle_command
示例#4
0
文件: alarm.py 项目: ccullin/alarmbot
 def __init__(self,
              name,
              device,
              passcode,
              mqtt_host,
              speed=115200,
              **kwargs):
     log.debug(kwargs)
     self.name = name
     self.passcode = passcode
     self.port = serial.serial_for_url(device, baudrate=speed, timeout=0)
     self.broker = mqtt_host
     self.dcs1500state = 'unknown'
     self.status = 'unknown'
     self.lastStatus = 'unknown'
     self.mqtt = MQTT(broker=self.broker, name=self.name, menu=self.command)
示例#5
0
class AddOhmsBot(BaseBot):
    MQTT = MQTT()
    msg_prefix = "🤖 "
    ATTN_ENABLE = True
    live = False
    location = "Lab"

    def __init__(self):
        super().__init__()

        # Load the ignore list from the database on startup
        self.ignore_list_patterns = dict()
        query = session.query(IgnoreList).filter(
            IgnoreList.enabled == True).all()  # noqa E712
        for each in query:
            self.ignore_list_patterns[each.id] = each.pattern

        # Check and set the status of the bot on startup.
        AddOhmsBot.live = self.check_live_status()
        print(f"Stream online: {AddOhmsBot.live}")

    def check_live_status(self):
        """This is NOT an Asynchronous Function. Do not use it once the bot is online."""

        # Check the stream status on startup
        url = f"https://api.twitch.tv/helix/streams?user_login={cfg.channels[0]}"

        headers = {
            "client-id": get_client_id(),
            "Authorization": f"Bearer {get_oauth(remove_prefix=True)}",
        }

        r = requests.get(url=url, headers=headers)
        data = loads(r.text)
        if data.get("error", False):
            print(f"{data['status']} {data['message']}")
            _exit(0)

        data = data["data"]
        if len(data) > 0:
            data = data[0]
            if data["type"] == "live":
                return True
            else:
                return False
        else:
            return False

    def user_ignored(self, username: str) -> bool:
        """Returns True if the user is on the ignore list"""
        for pattern in self.ignore_list_patterns.values():
            if re.match(pattern, username):
                print(
                    f"Ignoring command from {username} matching pattern {pattern}"
                )
                return True

        # Nothing matched, so return False
        return False
示例#6
0
class Receiver():
    def __init__(self):
        info('receiver', 'init')
        self.queue = Queue()
        self.mqtt = MQTT(os.environ['KIT_CHANNEL'],
                         client_id='receiver-mqtt',
                         queue=self.queue)
        self.running = False

    # Start the signer.
    def start(self, pipe):
        info('receiver', 'start')
        self.mqtt.connect(os.environ['KIT_MQTT_HOST'],
                          int(os.environ['KIT_MQTT_PORT']),
                          os.environ['KIT_DEVICE_ID'],
                          os.environ['KIT_DEVICE_KEY'])
        while not self.mqtt.connected:
            info('receiver', 'waiting for connection')
            time.sleep(1)
        info('receiver', 'connected')

        self.pipe = pipe
        self.running = True

        while self.running:
            # Check the queue for a received message.
            msg = self.queue.get()

            # If for this device then pass to controller.
            if msg.is_valid() and msg.for_device():
                info('receiver', 'queue: ' + str(msg))
                self.pipe.send(msg)

    # Stop the signer.
    def stop(self):
        info('receiver', 'stop')
        self.running = False

        try:
            self.mqtt.disconnect()
            #self.pipe.close()
        except Exception as ex:
            error('receiver', 'stop error: ' + str(ex))
示例#7
0
    def __init__(self, board, network, scheduler):
        self.board = board
        self.scheduler = scheduler
        self.parts_initialized = False
        self.mac = network.mac
        self.data = {}
        self.mine = None
        self.version = "0.8.0"
        self.listeners = []
        self.read_cache()
        #        if (type(self.mine) is dict and "parts" in self.mine):
        #            ct.print_heading("initializing from cache")
        #            Part.init_parts(board, scheduler, self.mine["parts"])

        Component.setup_services(board, scheduler)
        if (type(self.mine) is dict and "components" in self.mine):
            ct.print_heading("initializing from cache")
            Component.netlist_from_config(self.mine["components"])
            Component.print_netlist()
        MQTT.subscribe(config_topic_base + self.mac + "/config", self.on_mqtt)
示例#8
0
class BotController(object):
    def __init__(self, config):
        self.broker = config.get('mqtt_host')
        self.name = config.get('name')
        self.keysDB = Mongodb(**config.get('mongodb'))
        self.bots = {}
        self.config = config.get('webAPI')
        self.api = webAPI(self.config)

    def run(self):
        self.api.registerController()
        for bot, config in self.config.get('bots').items():
            self.bots[bot] = Bot(bot, config, self.keysDB)
            r = self.api.subscribeBot(**self.bots[bot].credentials)
            log.debug("subscription response code = '{}".format(r))
        self.mqtt = MQTT(self.broker, name=self.name, botController=self)

    def newCommand(self, command):
        log.debug('command = {}'.format(command))
        botWebName = command.get('recipient')
        bot = self.keysDB.getBotName(botWebName)
        log.debug("webName= {}, bot= {}".format(botWebName, bot))
        if bot:
            r = self.mqtt.publish(bot + '/command', str(command))
            log.debug("response: '{}'".format(r))
        else:
            log.error("BotWebName '{}' not found".format(botWebName))

    def sendMessage(self, message, sender, recipientId):
        bot = self.keysDB.getBotName(sender)
        log.debug("sending message: {} {} {} {}".format(
            bot, sender, recipientId, message))
        self.api.sendMessage(messageText=message,
                             recipientId=recipientId,
                             **self.bots[bot].credentials)

    def sendEvent(self, sender, message):
        for admin, adminId in self.bots[sender].admins.items():
            log.debug("sending message: {} {} {} {}".format(
                sender, message, admin, adminId))
            self.api.sendMessage(messageText=message,
                                 recipientId=adminId,
                                 **self.bots[sender].credentials)

    def updateDB(self, webName, credentials):
        for bot in self.bots:
            if self.bots[bot].webName == webName:
                self.keysDB.storeConfig(bot, webName, credentials)
                return ('Successfully updated config')
        return (
            'device not config for botCOntroller, See system administrator')
示例#9
0
    def __init__(self, *args, **kw):

        tk.Tk.__init__(self)

        self.mqtt = MQTT()
        self.db = DB()
        self.regexEmail = re.compile(
            r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")

        # print(self.users)

        self.user = None
        self.trajetos = []

        self.email = tk.StringVar()
        self.passwd = tk.StringVar()

        self.iconbitmap('img/favicon.ico')
        self.resizable(width=False, height=False)

        self.width = self.winfo_screenwidth() // 2
        self.height = self.winfo_screenheight() // 2
        self.geometry(f"360x640+{self.width - 400}+{self.height - 350}")
        # self.splashScreen = SplashScreen(self)

        self.imgBgOriginal = Image.open('img/bg.png')
        self.imgBgResize = self.imgBgOriginal.resize((360, 640),
                                                     Image.ANTIALIAS)

        self.imgBg = ImageTk.PhotoImage(self.imgBgResize)

        self.imgBgLabel = tk.Label(self, image=self.imgBg)
        self.imgBgLabel.place(x=0, y=0)

        self.withdraw()
        self.screen = HomePage(self)
示例#10
0
文件: alarm.py 项目: ccullin/alarmbot
class Alarm(object):
    def __init__(self,
                 name,
                 device,
                 passcode,
                 mqtt_host,
                 speed=115200,
                 **kwargs):
        log.debug(kwargs)
        self.name = name
        self.passcode = passcode
        self.port = serial.serial_for_url(device, baudrate=speed, timeout=0)
        self.broker = mqtt_host
        self.dcs1500state = 'unknown'
        self.status = 'unknown'
        self.lastStatus = 'unknown'
        self.mqtt = MQTT(broker=self.broker, name=self.name, menu=self.command)

    def start(self):
        self.thread = Thread(name="alarm_monitor", target=self.__monitor)
        self.event = threading.Event()
        self.thread.start()
        self.__monitor()

    def stop(self):
        self.mqtt.loop_stop()
        self.mqtt.disconnect()
        self.event.set()

    def __readSerial(self):
        buffer_string = ''
        while not self.event.is_set():
            self.event.wait(timeout=1.0)
            buffer_string = buffer_string + self.port.read(
                self.port.inWaiting()).decode(('utf-8'))
            if '\n' in buffer_string:
                timestamp = datetime.today().isoformat()
                lines = buffer_string.split('\n')
                last_received = lines[-2]  # Last full line.
                buffer_string = lines[-1]  # First part of next line.
                self.dcs1500state = last_received
                self.alarmTime = timestamp
                break

    def __get_status(self):
        """
        Monitors serial port until there is a full update from the arduino.Monitors
        """
        self.__readSerial()
        if self.dcs1500state[21:26] == 'Armed':
            self.status = 'ARMED'
            if self.dcs1500state[39] == 'A':
                self.status = 'TRIPPED'
        elif self.dcs1500state[1:3] == 'RA':
            self.status = 'ARMING'
        else:
            self.status = 'DISARMED'
        pass

    def __monitor(self):
        log.debug("started Monitor")
        while not self.event.is_set():
            self.event.wait(timeout=1.0)
            self.__get_status()
            if self.status != self.lastStatus:
                self.sendEventNotification("alarm is {}, previously {}".format(
                    self.status, self.lastStatus.lower()))
                log.info(
                    "alarm status change to: {}  previous status: {}".format(
                        self.status, self.lastStatus))
                self.lastStatus = self.status

    def __on(self):
        self.port.write(self.passcode.encode())

    def __off(self):
        self.port.write(self.passcode.encode())

    def get_status(self):
        return self.status

    def sendEventNotification(self, msg):
        message = {
            "recipientId": "admins",
            "sender": self.name,
            "message": msg
        }
        try:
            log.debug("publish {}/event msg: {}".format(
                self.name, str(message)))
            self.mqtt.publish(self.name + "/event", str(message))
        except requests.exceptions.ConnectionError as e:
            log.warning("Connection Error: {}".format(e))
            pass

    def command(self, cmd, respond):
        command = cmd.lower()

        if self.status == 'unknown':
            self.get_status()
            respond('connot process command at this time')
        elif command == 'off':
            if self.status != 'DISARMED':
                self.__off()
                respond('alarm turning off')
            else:
                respond('alarm already off')
        elif command == 'on':
            if self.status == 'DISARMED':
                self.__on()
                respond('alarm turning on')
            else:
                respond('alarm aLready on')
        elif command == 'hi':
            respond(self.get_status())
        else:
            respond('invalid command')
示例#11
0
文件: py.py 项目: luxuntong/mqtt
def on_message(client, userdata, msg):
    print(msg.topic + " " + msg.payload.decode("utf-8"))
    jsonData = json.loads(msg.payload.decode("utf-8"))
    MQTT().setInfo(jsonData)
示例#12
0
 def first_eval(self):
     MQTT.publish(self.name, self.input.value, True, True)
示例#13
0
@app.route("/", methods=["POST"])
def setLight():
    data = request.get_json()
    red = int(data["red"])
    blue = int(data["blue"])
    green = int(data["green"])

    setLightValues(red, gree, blue)

    return str(red) + ", " + str(green) + ", " + str(blue)


def setLightValues(red, green, blue):
    led.setRed(red)
    led.setGreen(green)
    led.setBlue(blue)
    mqtt.publish_rgb_state(red, green, blue)


mqtt = MQTT(setLightValues)

if __name__ == "__main__":
    mqttBroker = os.environ.get("MQTT_BROKER")
    mqttUser = os.environ.get("MQTT_USER")
    mqttPass = os.environ.get("MQTT_PASSWORD")
    if (mqttBroker == None):
        print("No MQTT broker set, starting in HTTP mode")
        app.run(host='0.0.0.0')
    else:
        mqtt.connect(mqttBroker, mqttUser, mqttPass)
示例#14
0
from flask import Flask, jsonify
import navigation
from map_render import *

from mqtt import MQTT

app = Flask(__name__)

mqtt_service = MQTT()


@app.route('/directions/<start>/<dest>', methods=['GET'])
def directions(start, dest):

    try:
        nodes = navigation.g.shortest_path(start, dest)
        direction = navigation.generate_route(nodes)
        map_render = str(render_map(nodes))
        mqtt_service.publish_msg(str(nodes))
        error_code = ""

    except Exception as e:
        error_code = str(e)

    response = {
        "direction": direction,
        "map_render": map_render,
        "error": error_code
    }

    return jsonify(response)
示例#15
0
#!/usr/bin/python3
"""
    Program that handles chromecast integration, mainly with domoticz. But also implements
    a crude rest api for controlling a chromecast, and start streaming pre-defined streams.

    This can be used to create a web interface for controlling a chromecast (for example in
    angular)

    Copyright 2018: Thomas Bowman Mørch
"""
import pychromecast
from chromeevent import ChromeEvent
from mqtt import MQTT

mqtt = MQTT()
mqtt.subscriptions = []
mqtt.conn()
mqtt.loop_start()

CASTS = pychromecast.get_chromecasts()
c = CASTS[2]
e = ChromeEvent(c, 'Global', mqtt)

e.new_cast_status(e.device.status)


for

if len(CASTS) == 0:
    print("No Devices Found")
    exit()
示例#16
0
 def init_param(cls, value, component, param_name):
     assert param_name == "input", "the only parameter of an input_pin must be named 'input'"
     MQTT.subscribe(value, component.callback, True)
示例#17
0
from mongo import Mongo
from mqtt import MQTT
from signal import pause

mongo = Mongo()
mqtt = MQTT(mongo)

mongo.connect()
mqtt.run()

try:
    pause()
except KeyboardInterrupt:
    pass

mqtt.stop()
mongo.disconnect()
示例#18
0
 def on_input_change(self, signal):
     if (signal == self.strobe
             or (signal == self.input and self.auto.value >= 0.5)):
         MQTT.publish(self.name, self.input.value, True, True)
示例#19
0
class Coordinator:

    ########## Constructor ##########

    def __init__(self):
        self.ac_on = False

        self._init_logger()
        self._init_neopixel()
        self._init_ir()

        self._init_mqtt()
        self._init_lock()
        self._init_rfid()
        self._initialise_volume_control()
        self._initialise_ac()
        self._initialise_brightness_control()
        self._init_buttons()

        self._mqtt_client.send_message("boot", "started")
        self.strip.set_mode(Effects.RGB)

########## Logger ##########

    def _init_logger(self):
        self.formatter = logging.Formatter(
            fmt='%(asctime)s %(levelname)-8s %(message)s',
            datefmt='%Y-%m-%d %H:%M:%S')
        self.handler = RotatingFileHandler(
            filename='/home/pi/app/coffee_table.log',
            mode='a',
            maxBytes=20 * 1024 * 1024,
            backupCount=2,
            encoding=None,
            delay=0)
        self.handler.setFormatter(self.formatter)
        self.logger = logging.getLogger("coffee_table")
        self.logger.setLevel(logging.DEBUG)
        self.logger.addHandler(self.handler)
        self.logger.debug("Starting coordinator Service")

########## Lock ##########

    def _init_lock(self):
        self.lock = OutputDevice(HAL.LOCK)
        self.lock.off()

    def open_lock(self, time_s):
        self.strip.pause()
        self.lock.on()
        threading.Timer(time_s, self.close_lock).start()

    def close_lock(self):
        self.lock.off()
        self.strip.unpause()

########## RFID Reader ##########

    def _init_rfid(self):
        self._reader = RFID(self.logger)
        self._reader.on_tag = lambda sender, tag: self._mqtt_client.send_message(
            "tags", tag)
        self._reader.start()

########## IR ##########

    def _init_ir(self):
        self.comms = Comms()
        self.device_state_tv = False
        self.device_state_amp = False
        self.remote = Remote(1, Config.REMOTE_AMP, self.logger, self.comms)

    def turn_on_devices(self):
        if not self.device_state_tv:
            self.remote.press_button(Key.TV_POWER, 1)
            self.device_state_tv = not self.device_state_tv
        if not self.device_state_amp:
            self.remote.press_button(Key.AMP_POWER, 1)
            self.device_state_amp = not self.device_state_amp

########## Room Lights ##########

    def _initialise_brightness_control(self):
        self.lights_held = False
        self.sine = Sine()
        self.rgb_mode_timer = threading.Timer(Config.RGB_MODE_TIMER,
                                              self.leave_rgb_mode)
        self.lights_tx_timer = threading.Timer(Config.LIGHTS_DELAY_TO_SEND,
                                               self.lights_send_brightness)
        self.lights_are_on = True
        self.brightness = 0xFF
        self.rgb_long = 0x00FFFFFF
        self.brightness_control = RotaryEncoder(HAL.LIGHTS_A,
                                                HAL.LIGHTS_B,
                                                maximum=255,
                                                minimum=0,
                                                initial=255,
                                                step_size=5)
        self.brightness_control.on_clockwise = self.brightness_up
        self.brightness_control.on_counter_clockwise = self.brightness_down
        self._mqtt_client.on_rgb = self.on_rgb_message

        self.btn_lights = Button(HAL.LIGHTS_C, pull_up=True)
        self.btn_lights.hold_time = Config.BTN_HOLD_TIME
        self.btn_lights.when_held = self.enter_rgb_mode
        self.btn_lights.when_released = self.toggle_lights
        self.rgb_angle = 0

    def brightness_up(self):
        self.strip.set_temperature(self.brightness_control.percent())
        self.lights_tx_timer.cancel()
        self.lights_tx_timer = threading.Timer(Config.LIGHTS_DELAY_TO_SEND,
                                               self.lights_send_brightness)
        self.lights_tx_timer.start()

    def brightness_down(self):
        self.strip.set_temperature(self.brightness_control.percent())
        self.lights_tx_timer.cancel()
        self.lights_tx_timer = threading.Timer(Config.LIGHTS_DELAY_TO_SEND,
                                               self.lights_send_brightness)
        self.lights_tx_timer.start()

    def rgb_angle_changed(self):
        self.rgb_angle = self.brightness_control.value
        self.colour_picker = self.sine.get_triangle(self.rgb_angle *
                                                    Config.DEGREES_PER_CLICK)
        self.strip.pixels.fill(self.colour_picker)
        self.strip.pixels.show()

        self.lights_tx_timer.cancel()
        self.lights_tx_timer = threading.Timer(Config.LIGHTS_DELAY_TO_SEND,
                                               self.lights_send_rgb)
        self.lights_tx_timer.start()

        self.rgb_mode_timer.cancel()
        self.rgb_mode_timer = threading.Timer(Config.RGB_MODE_TIMER,
                                              self.leave_rgb_mode)
        self.rgb_mode_timer.start()

    def lights_send_brightness(self):
        print("Updating Brightness")
        self._mqtt_client.send_message("lights/brightness",
                                       format(self.brightness_control.value))

    def lights_send_rgb(self):
        string = ",".join(str(x) for x in self.colour_picker)
        print("Updating RGB")
        self._mqtt_client.send_message("lights/rgb", string)

    def enter_rgb_mode(self):
        self.lights_held = True
        self.strip.set_mode(Effects.RGB)
        self.strip.blink(0, 0, 255)
        self.rgb_mode_timer.cancel()
        print("RGB Mode")
        self.strip.set_brightness(1)
        self.brightness_control.loop = True
        self.brightness_control.maximum = round(
            360 / Config.DEGREES_PER_CLICK) - 1
        self.brightness_control.step = 1
        self.brightness_control.value = self.rgb_angle
        self.brightness_control.on_clockwise = None
        self.brightness_control.on_counter_clockwise = None
        self.brightness_control.on_value_change = self.rgb_angle_changed
        self.rgb_mode_timer.cancel()
        self.rgb_mode_timer = threading.Timer(Config.RGB_MODE_TIMER,
                                              self.leave_rgb_mode)
        self.rgb_mode_timer.start()

    def leave_rgb_mode(self):
        self.rgb_mode_timer.cancel()
        print("Normal Mode")
        self.brightness_control.loop = False
        self.brightness_control.maximum = 255
        self.brightness_control.step = 5
        self.brightness_control.value = 255
        self.brightness_control.on_clockwise = self.brightness_up
        self.brightness_control.on_counter_clockwise = self.brightness_down
        self.brightness_control.on_value_change = None
        self.rgb_mode_timer.cancel()
        self.strip.restore()

    def toggle_lights(self):
        if (self.lights_held):
            self.lights_held = False
            return
        self._mqtt_client.send_message("lights/brightness", "toggle")

    def on_rgb_message(self, r, g, b):
        self.strip.set_colour(r, g, b, transient=False, dim_after=5)

########## Neopixel ##########

    def _init_neopixel(self):
        self.strip = Indicator(HAL.WS2812B_DATA, 55)
        self.strip.set_mode(Effects.CYLON)
        self.effect = 1

    def cycle_effect(self):

        if self.effect == 0:
            self.strip.set_mode(Effects.RGB)

        if self.effect == 1:
            self.strip.set_mode(Effects.FIRE)

        if self.effect == 2:
            self.strip.set_mode(Effects.METEOR)

        if self.effect == 3:
            self.strip.set_mode(Effects.CYLON)

        if self.effect == 4:
            self.strip.set_mode(Effects.RGB)
            self.strip.set_colour(40, 0, 0, False)

        if self.effect == 5:
            self.strip.set_mode(Effects.RGB)
            self.strip.set_colour(0, 40, 0, False)

        if self.effect == 6:
            self.strip.set_mode(Effects.RGB)
            self.strip.set_colour(0, 0, 40, False)
            self.effect = -1

        self.effect += 1

########## Volume ##########

    def _initialise_volume_control(self):
        self.receiver = eiscp.eISCP('192.168.1.31')
        self.source = 1
        self.tv_mode = False
        self.volume_power_held = False

        self.button_amp_power = Button(HAL.VOL_C, pull_up=True)
        self.button_amp_power.hold_time = Config.BTN_HOLD_TIME
        self.button_amp_power.when_held = self.btn_volume_held
        self.button_amp_power.when_released = self.btn_volume_release

        self.volume_control = RotaryEncoder(HAL.VOL_A,
                                            HAL.VOL_B,
                                            maximum=60,
                                            minimum=0,
                                            initial=30,
                                            step_size=1)
        self.volume_control.on_clockwise = self.volume_up
        self.volume_control.on_counter_clockwise = self.volume_down
        self.btnvol_was_held = False

    def btn_volume_held(self):
        self.btnvol_was_held = True
        self.strip.blink(0, 0, 255)

    def btn_volume_release(self):
        if not self.btnvol_was_held:
            self._mqtt_client.send_message("amp", "short")
        else:
            self._mqtt_client.send_message("amp", "long")
        self.btnvol_was_held = False

    def switch_mode(self):
        self.tv_mode = not self.tv_mode

    def volume_up(self):
        self.strip.set_temperature(self.volume_control.percent())
        self.receiver.send('MVLUP')

    def volume_down(self):
        self.strip.set_temperature(self.volume_control.percent())
        self.receiver.send('MVLDOWN')

########## Aircon ##########

    def _initialise_ac(self):
        self.ac_power = Button(HAL.AC_C, pull_up=True)
        self.ac_control = RotaryEncoder(HAL.AC_A,
                                        HAL.AC_B,
                                        maximum=30,
                                        minimum=16,
                                        initial=24,
                                        step_size=1,
                                        can_zero=False)
        self.ac_control.on_value_change = self.set_ac
        self.ac_power.when_released = self.toggle_ac
        self.ac_timer = threading.Timer(Config.AIRCON_DELAY_TO_SEND,
                                        self.send_ac_temp)
        self._mqtt_client.on_ac_temp = self.update_temp

    def update_temp(self, temp):
        self.ac_control.value = int(temp)
        self.strip.set_temperature(self.ac_control.percent())

    def set_ac(self):
        self.strip.set_temperature(self.ac_control.percent())
        self.ac_timer.cancel()
        self.ac_timer = threading.Timer(Config.AIRCON_DELAY_TO_SEND,
                                        self.send_ac_temp)
        self.ac_timer.start()

    def send_ac_temp(self):
        self._mqtt_client.send_message("ac/set_temp",
                                       format(self.ac_control.value))

    def toggle_ac(self):
        self._mqtt_client.send_message("btnAC", "click")

########## Buttons ##########

    def _init_buttons(self):
        self.btn1 = Button(HAL.BTN1, pull_up=True)
        self.btn1.when_held = self.btn1_held
        self.btn1.when_released = self.btn1_release
        self.btn1_was_held = False
        self.btn2 = Button(HAL.BTN2, pull_up=True)
        self.btn2.when_held = self.btn2_held
        self.btn2.when_released = self.btn2_release
        self.btn2_was_held = False
        self.btn3 = Button(HAL.BTN3, pull_up=True)
        self.btn3.when_held = self.btn3_held
        self.btn3.when_released = self.btn3_release
        self.btn3_was_held = False
        self.btn4 = Button(HAL.BTN4, pull_up=True)
        self.btn4.when_held = self.btn4_held
        self.btn4.when_released = self.btn4_release
        self.btn4_was_held = False
        self.btn5 = Button(HAL.BTN5, pull_up=True)
        self.btn5.when_held = self.btn5_held
        self.btn5.when_released = self.btn5_release
        self.btn5_was_held = False
        self.btn6 = Button(HAL.BTN6, pull_up=True)
        self.btn6.when_held = self.btn6_held
        self.btn6.when_released = self.btn6_release
        self.btn6_was_held = False

    # LED Fun
    def btn1_held(self):
        self.btn1_was_held = True
        self._mqtt_client.send_message("btn1", "hold")
        self.strip.blink(0, 0, 255)

    def btn1_release(self):
        if not self.btn1_was_held:
            self._mqtt_client.send_message("btn1", "click")
            self.cycle_effect()
        self.btn1_was_held = False

    # Button 2
    def btn2_held(self):
        self.btn2_was_held = True
        self._mqtt_client.send_message("btn2", "hold")
        self.strip.blink(0, 0, 255)

    def btn2_release(self):
        if not self.btn2_was_held:
            self._mqtt_client.send_message("btn2", "click")
            print("Btn2 released")
        self.btn2_was_held = False

    def btn3_held(self):
        self.btn3_was_held = True
        self._mqtt_client.send_message("btn3", "hold")
        self.strip.blink(0, 0, 255)

    def btn3_release(self):
        if not self.btn3_was_held:
            self._mqtt_client.send_message("btn3", "click")
            print("Btn3 released")
        self.btn3_was_held = False

    def btn4_held(self):
        self.btn4_was_held = True
        self._mqtt_client.send_message("btn4", "hold")
        self.strip.blink(0, 0, 255)

    def btn4_release(self):
        if not self.btn4_was_held:
            self._mqtt_client.send_message("btn4", "click")
            print("Btn4 released")
        self.btn4_was_held = False

    #Play/Pause TV
    def btn5_held(self):
        self.btn5_was_held = True
        self._mqtt_client.send_message("btn5", "hold")
        self.strip.blink(0, 0, 255)

    def btn5_release(self):
        if not self.btn5_was_held:
            self._mqtt_client.send_message("btn5", "click")
            print("Btn5 released")
        self.btn5_was_held = False

    # PC On/Off
    def btn6_held(self):
        self.btn6_was_held = True
        self._mqtt_client.send_message("btn6", "hold")
        self.strip.blink(0, 0, 255)

    def btn6_release(self):
        if not self.btn6_was_held:
            self._mqtt_client.send_message("btn6", "click")
            print("Btn6 released")
        self.btn6_was_held = False

########## Command Handler ##########

    def handle_command(self, command):
        if command == "unlock":
            self.open_lock(Config.OPEN_LOCK_TIME)
        elif command == "lock":
            self.lock.off()
        elif command == "fire":
            self.strip.set_mode(Effects.FIRE)
        elif command == "cylon":
            self.strip.set_mode(Effects.CYLON)
        elif command == "stop_rgb":
            self.strip.set_mode(Effects.RGB)
            self.strip.set_colour(0, 10, 0, False)
        elif command == "devices_on":
            self.turn_on_devices()
        elif command == "source_cd":
            self.remote.press_button(Key.AMP_CD, 1)
            self.source = 2
        elif command == "source_video1":
            self.remote.press_button(Key.AMP_VIDEO1, 1)
            self.source = 3
        elif command == "source_video2":
            self.remote.press_button(Key.AMP_VIDEO2, 1)
            self.source = 4
        elif command == "source_aux":
            self.remote.press_button(Key.AMP_AUX, 1)
            self.source = 1
        elif command == "amp_power":
            self.remote.press_button(Key.AMP_POWER, 1)
        elif command == "tv_power":
            self.remote.press_button(Key.TV_POWER, 1)
        elif command == "pause":
            self.remote.press_button(Key.TV_PAUSE, 1)
        elif command == "play":
            self.remote.press_button(Key.TV_PLAY, 1)
        else:
            self.logger.debug("unrecognized command: " + command)

########## MQTT ##########

    def _init_mqtt(self):
        self._mqtt_client = MQTT(secrets.mqtt_broker, secrets.mqtt_port,
                                 secrets.mqtt_user, secrets.mqtt_pass,
                                 self.logger)
        self._mqtt_client.start()

        while self._mqtt_client.connected != True:
            time.sleep(0.1)

        self._mqtt_client.send_message("buttons", "Running")
        self._mqtt_client.send_message("lights/lounge", "update")
        self._mqtt_client.on_command = self.handle_command


########## Main ##########

    def run(self):
        try:
            pause()

        except KeyboardInterrupt:
            self._reader.stop()
            self._mqtt_client.stop()

            self.logger.info("App closing")
示例#20
0
from mqtt import MQTT
from temp_control import T_control
from od_sensor import ODSensor
from time import sleep
from display import Display

if __name__ == "__main__":

    # class declarations
    broker = MQTT("Asger","1234567890") 
    t_control = T_control(14,32,12,34)
    t_control.startPID()
    od = ODSensor(25,39)
    disp = Display(22,23)

    def subCB(topic, msg):
        topic = str(topic)
        
        if "PID_P" in topic:
            t_control.pid.Kp = float(msg)
        elif "PID_I_SetValue" in topic:
            t_control.pid.history = float(msg) / t_control.pid.Ki    
        elif "PID_I" in topic:
            t_control.pid.Ki = float(msg)
            print(msg)
        elif "FAN" in topic:
            if msg.decode() == "OFF":
                t_control.cooler.fanOff()
            else:
                t_control.cooler.fanOn()
        elif "target_temp" in topic:
示例#21
0
文件: main.py 项目: luxuntong/mqtt
async def cmd(request):
    data = await request.json()
    print(data)
    print(MQTT().GPSPools)
    if 'name' not in data:
        return web.json_response({'error': '"name" is a required field'})
示例#22
0
from socket import *
from uuid import UUID
from mqtt import MQTT
from decrypt import decrypt
import cfg

cfg = cfg.load()
mqtt = MQTT()

s = socket(AF_INET, SOCK_DGRAM)
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
s.bind(('', 17117))

while True:
    data = s.recv(1024)
    data = decrypt(data)
    # if no valid data was received
    if data == None:
        continue

    # print(data.hex(' '))

    # check first two bytes of mac, they must be 0x17 and 0x00
    mac = data[0:6]
    if mac[0] != 0x17 and mac[1] != 0x00:
        continue

    # battery state (percent)
    if data[10] > 0:
        mqtt.publish('sensor/0x%s/battery/state' % (mac.hex()), data[10])
示例#23
0
#!/usr/bin/python
from sense_hat import SenseHat
from mqtt import MQTT
import time
import sys
sense = SenseHat()
mqtt = MQTT("lgvohswk", "VcimBX_iUvkb")
sense.clear()
try:
    while True:
        temp = sense.get_temperature()
        temp = round (temp, 1)
        print("Temperature C", temp)
        mqtt.publish("temperature", temp)
        #sense.show_message(str(temp))

        humidity = sense.get_humidity()
        humidity = round (humidity,1)
        print("Humidity", humidity)
        mqtt.publish("humidity", humidity)

        pressure = sense.get_pressure()
        pressure = round (pressure,1)
        print("Pressure", pressure)
        mqtt.publish("pressure", pressure)

        time.sleep(1)
except KeyboardInterrupt:
    pass
示例#24
0
import datetime
import socket

devlist = {'FILE': 'DEVLIST', 'RASPID': str(rasp_info.rasp_get_id())}
devdata = {'FILE': 'DEVDATA', 'RASPID': str(rasp_info.rasp_get_id())}
rulelist = {'FILE': 'RULELIST', 'RASPID': str(rasp_info.rasp_get_id())}
rs485Lock = threading.Lock()
devlistLock = threading.Lock()
devdataLock = threading.Lock()
rulelistLock = threading.Lock()
mqttLock = threading.Lock()

tpin = rasp_info.rasp_get_id() + '/m2s'
tpout = rasp_info.rasp_get_id() + '/s2m'
modbus = Modbus('/dev/ttyUSB0')
mqtt = MQTT('iot.eclipse.org', 1883, tpin, tpout)


class threadDeviceManager(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        global devlist
        while True:
            rs485Lock.acquire(1)
            devlistLock.acquire(1)
            devdataLock.acquire(1)
            start_time = datetime.datetime.now()
            print('Start scanning for lost device...')
            dev2remove = []
示例#25
0
from board.bohei import Board
from config import Config
from display import Display
from ewh_net import Network
from heartbeat import Heartbeat
from name import Name
from mqtt import MQTT
from task import Scheduler
import ntptime

network = Network()
MQTT.init(network)

board = Board(network)
board.init()

heartbeat = Heartbeat(board.display)

scheduler = Scheduler()

config = Config(board, network, scheduler)

name = Name(config, board.display)
scheduler.register(board.display)
scheduler.register(heartbeat)
scheduler.register(network)
scheduler.register(MQTT.task)

print("Starting scheduler of version {0}".format(config.version))

scheduler.start(100)
示例#26
0
 def genHtml(self, jsonData):
     MQTT().generateHtml()
示例#27
0
for o, a in opts:
    if o == '-s':
        topic_list = a.split(",")
    elif o == '-u':
        user = a
    elif o == '-p':
        password = a
    else:
        assert False, "unhandled option"

if topic_list is None:
    print("Client not subscribed to any topics!")
    usage()
    sys.exit(2)

mqttc = MQTT(user, password)

def on_message(mqttc, obj, msg):
    print(msg.topic + " " + str(msg.qos) + " " + str(msg.payload))
    if msg.topic == "temperature":
    	with open("temperature.txt", "a") as file:
            print("Writing into temperature.txt")
            file.write(msg.payload)
            file.write("\n")
            file.close()
    elif msg.topic == "humidity":
    	with open("humidity.txt", "a") as file:
            print("Writing into humidity.txt")
            file.write(msg.payload)
            file.write("\n")
            file.close()
示例#28
0
def handle_stop_signals(signum, frame):
    global running
    print("Received signal %d." % signum)
    running = False


running = True
rx_buffer = deque(maxlen = 10)

with Radio(FREQ_433MHZ, conf.node_id, conf.network_id, isHighPower=True, power=conf.radio_power,
           interruptPin=conf.interrupt_pin, resetPin=conf.reset_pin, spiBus=conf.spi_bus, spiDevice=conf.spi_device,
           autoAcknowledge=False) as radio:
    signal.signal(signal.SIGINT, handle_stop_signals)
    signal.signal(signal.SIGTERM, handle_stop_signals)

    print("rfm69-mqtt-gateway starting..")
    print("Used configuration:")
    pprint(conf.__dict__)

    mqtt = MQTT(conf.mqtt_broker, conf.tx_subs_topic)

    while running:
        forward_from_radio_to_mqtt(radio, mqtt)
        forward_from_mqtt_to_radio(mqtt, radio)
        time.sleep(0.005)

    print("Disconnecting MQTT.")
    mqtt.disconnect()

print("Exiting.")
示例#29
0
from flask import Flask
from flask import render_template, request, redirect, url_for, jsonify, make_response
import threading
import atexit
import json
from mqtt import MQTT

mqtt = MQTT()
app = Flask(__name__)
app.config['DEBUG']=False
@app.route('/send_pump_signal', methods=['POST'])
def send_pump_signal():
    value = request.form['value']
    feed_id = request.form['feed_id']
    print(feed_id)
    value = {
        "id": "11", 
        "name": "RELAY", 
        "data": f"{value}",
        "unit": ""
    }

    mqtt.send_feed_data(feed_id, json.dumps(value))
    return 'OK'       

if __name__ == '__main__':
    app.run(port = 5000, debug = False)
#
# Example how to use dsmr parser with the SeNDlab Influx database
# and MQTT broker
#
#

#!/usr/bin/python3
import time, signal
from logger import logger
from mqtt import MQTT

from appconfig import AppConfig

appconfig = AppConfig()
mqtt = MQTT(config=appconfig)

# Main entry point
def run_program():
    while True:
       if not mqtt.isConnected():
           try:
               mqtt.run()
           except:
                logger.info(msg="Cant't connect to Broker, retry in 30 seconds")
       time.sleep(30.0)
       pass

# Handle system interrupts e.g. ctrl-c
def keyboardInterruptHandler(signal, frame):
    logger.info(msg = "KeyboardInterrupt (ID: {}) has been caught. Cleaning up...".format(signal))
    mqtt.stop()