def handle(self, *args, **options):
     now = datetime.datetime.now()
     current_time = now - datetime.timedelta(
         minutes=int(now.strftime("%M")),
         seconds=int(now.strftime("%S")),
         microseconds=int(now.strftime("%f")))
     r = requests.get(
         "http://desktopfw.weather.com/weather/local/FIXX0001?hbhf=48&ut=C")
     data = r.text
     data = xmltodict.parse(data)
     data = json.loads(json.dumps(data))
     for hour in data["weather"]["hbhf"]["hour"]:
         current_hour = int(hour["@h"])
         delta_to_processing_time = datetime.timedelta(hours=current_hour)
         timestamp = current_time + delta_to_processing_time
         Weather.objects.filter(date=timestamp,
                                hour=int(
                                    timestamp.strftime("%H"))).delete()
         a = Weather(date=timestamp,
                     hour=timestamp.hour,
                     icon=hour["icon"],
                     ppcp=int(hour["ppcp"]),
                     dewpoint=int(hour["dewp"]),
                     feels_like=int(hour["flik"]),
                     humidity=int(hour["hmid"]),
                     temperature=int(hour["tmp"]),
                     description=hour["t"],
                     wind_direction=hour["wind"]["t"],
                     wind_gust=hour["wind"]["gust"],
                     wind_speed=int(hour["wind"]["s"]))
         a.save()
     publish_ws("weather", get_weather_data())
Exemple #2
0
    def post(self, request, *args, **kwargs):
        action = kwargs.get("action")
        command = kwargs.get("command")
        if command == "update":
            start_time = request.POST.get("start_time").split(":")
            duration = request.POST.get("duration").replace("+", "").split(":")
            start_time = datetime.time(int(start_time[0]), int(start_time[1]))
            duration = int(duration[0]) * 3600 + int(duration[1]) * 60
            current_settings = json.loads(redis_instance.get("lightcontrol-program-%s" % action))
            current_settings["duration"] = duration
            current_settings["start_at"] = start_time.strftime("%H:%M")
            redis_instance.set("lightcontrol-program-%s" % action, json.dumps(current_settings))

            if "running" in request.POST:
                running = request.POST.get("running")
                running = running in ("true", "True", "1")
                redis_instance.set("lightprogram-%s-running" % action, running)
                if running:
                    for group in range(1, 5):
                        redis_instance.set("lightcontrol-state-%s-auto" % group, True)

            send_lightcontrol_command("program-sync", 0)
            data = get_lightprogram(action)
            publish_ws("lightcontrol-timed-%s" % action, data)
            return HttpResponse(json.dumps(data), content_type="application/json")
        elif command == "override-resume":
            for group in range(1, 5):
                redis_instance.set("lightcontrol-state-{group}-auto".format(group=group), True)
                send_lightcontrol_command("program-sync", 0)
                publish_ws("lightcontrol-timed-override", {"action": "resume"})

        # TODO: get and serialize program details
        item = get_lightprogram(action)
        return HttpResponse(json.dumps(item), content_type="application/json")
Exemple #3
0
def update_lightstate(group, brightness, color=None, on=True, **kwargs):
    if group == 0:
        for group_num in range(1, 5):
            update_lightstate(group_num, brightness, color, on, **kwargs)
        return

    logger.debug("Updating lightstate: group=%s, brightness=%s, color=%s, on=%s, kwargs=%s", group, brightness, color, on, kwargs)
    timed_ends_at = is_any_timed_running()
    if kwargs.get("important", True) != False:
        if timed_ends_at != False:
            time_until_ends = (timed_ends_at - timezone.now()).total_seconds() + 65
            logger.info("Setting timed lightcontrol override for %s until %s", group, time_until_ends)
            redis_instance.setex("lightcontrol-no-automatic-%s" % group, int(time_until_ends), True)
            publish_ws("lightcontrol_timed_override", {"action": "pause"})

    (state, _) = LightGroup.objects.get_or_create(group_id=group)
    if color is not None:
        state.color = color

    if brightness is not None:
        if state.color == "white":
            state.white_brightness = brightness
        else:
            state.rgbw_brightness = brightness
    state.on = on
    state.save()
    return state
    def handle(self, *args, **options):
        hsl = HSLApi(settings.HSL_USERNAME, settings.HSL_PASSWORD)
        now = timezone.now()
        Data.objects.filter(time__lte=now).delete()
        data = []
        for stop in Stop.objects.all():
            lines = Line.objects.filter(show_line=True, stop=stop)
            fetch_stop = False
            for line in lines:
                if line.is_valid():
                    fetch_stop = True
                    break
            if fetch_stop:
                departures = hsl.get_timetable(stop.stop_number)
                # O(n*m), this could be optimized.
                for line in lines:
                    for departure in departures:
                        if departure["line_number"] == line.line_number_raw:
                            timezone_aware = timezone.make_aware(
                                departure["timestamp"],
                                timezone.get_current_timezone())
                            a, created = Data.objects.get_or_create(
                                line=line, time=timezone_aware)
                            if created:
                                a.save()

        publish_ws("public-transportation", get_departures())
 def handle(self, *args, **options):
     co2 = float(open(settings.CO2_FILE).read())
     temperature = float(open(settings.TEMPERATURE_FILE).read())
     r.rpush("air-quality-co2", co2)
     r.rpush("air-quality-temperature", temperature)
     publish_ws("indoor_temperature", {"value": temperature})
     publish_ws("indoor_co2", {"value": co2})
Exemple #6
0
def run_timed_actions():
    """ Runs light programs """
    led = LedController(settings.MILIGHT_IP)
    now = timezone.now()

    allowed_groups = set()
    for group in range(1, 5):
        if redis_instance.get("lightcontrol-no-automatic-%s" % group) is None:
            allowed_groups.add(group)

    for item in LightAutomation.objects.filter(running=True):
        if not item.is_running(now):
            continue
        percent_done = item.percent_done(now)
        logger.debug("Running %s, done %s%%", item.action, percent_done)

        brightness = None # Set brightness

        if item.action == "evening" or item.action == "evening-weekend":
            brightness = int((1-percent_done)*100)
        elif item.action == "morning" or item.action == "morning-weekend":
            brightness = int(percent_done * 100)

        if not item.action_if_off:
            # Don't turn on lights
            for group in list(allowed_groups): # cast to list to avoid "Set changed size during iteration"
                group_item, _ = LightGroup.objects.get_or_create(group_id=group)
                if group_item.on == False:
                    allowed_groups.remove(group)
        logger.debug("Only run on %s", allowed_groups)

        if item.set_white:
            for group in allowed_groups:
                led.white(group)
                logger.debug("Set %s to white", group)
                update_lightstate(group, None, "white", important=False)
        if brightness:
            logger.debug("Setting brightness to %s%%", brightness)
            publish_ws("lightcontrol-timed-brightness-%s" % item.action, brightness)
            for group in allowed_groups:
                group_brightness = brightness
                group_item, _ = LightGroup.objects.get_or_create(group_id=group)
                if item.no_brighten:
                    logger.debug("Current brightness: %s%%", group_item.current_brightness)
                    if group_item.current_brightness is not None:
                        group_brightness = min(group_item.current_brightness, group_brightness)
                if item.no_dimming:
                    logger.debug("Current brightness: %s%%", group_item.current_brightness)
                    if group_item.current_brightness is not None:
                        group_brightness = max(group_item.current_brightness, group_brightness)
                if group_item.current_brightness:
                    if led.get_brightness_level(group_brightness) == led.get_brightness_level(group_item.current_brightness):
                        logger.debug("Not sending brightness update to %s: no difference in brightness level", group)
                        continue
                logger.debug("Setting %s to %s", (group, group_brightness))
                led.set_brightness(group_brightness, group)
                update_lightstate(group, group_brightness, important=False)
            set_destination_brightness()
Exemple #7
0
def initiate_delayed_shutdown():
    """ Initiate delayed shutdown

    Automatically cancel possible other delayed shutdowns.
    """
    cancel_delayed_shutdown()
    redis_instance.setex("display-control-command", 120, "off")
    display_task = run_display_command_task.apply_async(
        countdown=30, expires=120)
    redis_instance.set("display-control-task", display_task.task_id)
    publish_ws("shutdown", "delayed-shutdown")
Exemple #8
0
def initiate_delayed_shutdown():
    """ Initiate delayed shutdown

    Automatically cancel possible other delayed shutdowns.
    """
    cancel_delayed_shutdown()
    redis_instance.setex("display-control-command", 120, "off")
    display_task = run_display_command_task.apply_async(countdown=30,
                                                        expires=120)
    redis_instance.set("display-control-task", display_task.task_id)
    publish_ws("shutdown", "delayed-shutdown")
def cancel_delayed_shutdown():
    """ Cancels delayed shutdown, if one is running """
    display_task = redis_instance.get("display-control-task")
    redis_instance.delete("display-control-command")
    publish_ws("shutdown", "cancel-delayed")
    if display_task:
        celery_app.control.revoke(display_task)
        redis_instance.delete("display-control-task")
        logger.info("cancel_delayed_shutdown revoked %s", display_task)
        return display_task
    logger.info("cancel_delayed_shutdown did not find task to be revoked")
    return False
def cancel_delayed_shutdown():
    """ Cancels delayed shutdown, if one is running """
    display_task = redis_instance.get("display-control-task")
    redis_instance.delete("display-control-command")
    publish_ws("shutdown", "cancel-delayed")
    if display_task:
        celery_app.control.revoke(display_task)
        redis_instance.delete("display-control-task")
        logger.info("cancel_delayed_shutdown revoked %s", display_task)
        return display_task
    logger.info("cancel_delayed_shutdown did not find task to be revoked")
    return False
def run_display_command(cmd):
    """ Runs xset command. This method does not validate command, but it is escaped properly. """
    env = {"DISPLAY": ":0"}
    logger.info("Running display command %s", cmd)
    process = subprocess.Popen(["xset", "dpms", "force", cmd], env=env)
    content = None
    if cmd == "off":
        content = "display-off"
    elif cmd == "on":
        content = "display-on"
    process.wait()
    if content:
        cancel_delayed_shutdown()
        logger.info("Broadcasting display status: %s", content)
        publish_ws("shutdown", content)
Exemple #12
0
    def post(self, request, *args, **kwargs):
        action = kwargs.get("action")
        command = kwargs.get("command")
        if command == "update":
            start_time = request.POST.get("start_time").split(":")
            duration = request.POST.get("duration").replace("+", "").split(":")
            running = request.POST.get("running")
            if running == "true":
                running = True
            else:
                running = False
            start_time = datetime.time(int(start_time[0]), int(start_time[1]))
            duration = int(duration[0]) * 3600 + int(duration[1]) * 60
            item, created = LightAutomation.objects.get_or_create(
                action=action,
                defaults={
                    "start_time": start_time,
                    "duration": duration,
                    "running": running
                })
            if not created:
                item.start_time = start_time
                item.duration = duration
                item.running = running

            item.save()
            if is_any_timed_running() == False:
                # No timed lightcontrol is running (anymore). Delete overrides.
                for group in range(1, 5):
                    redis_instance.delete("lightcontrol-no-automatic-%s" %
                                          group)
                    publish_ws("lightcontrol_timed_override",
                               {"action": "resume"})
            else:
                run_timed_actions()
            return HttpResponse(json.dumps(get_serialized_timed_action(item)),
                                content_type="application/json")
        elif command == "override-resume":
            for group in range(1, 5):
                redis_instance.delete("lightcontrol-no-automatic-%s" % group)
                publish_ws("lightcontrol_timed_override", {"action": "resume"})
            run_timed_actions()
        instance = get_object_or_404(LightAutomation, action=action)
        item = get_serialized_timed_action(instance)
        return HttpResponse(json.dumps(item), content_type="application/json")
def run_display_command(cmd):
    """ Runs xset command. This method does not validate command, but it is escaped properly. """
    env = {"DISPLAY": ":0"}
    logger.info("Running display command %s", cmd)
    if settings.RUN_XSET is False:
        logger.warn("Skipping xset, as RUN_XSET is False")
    else:
        process = subprocess.Popen(["xset", "dpms", "force", cmd], env=env)
        process.wait()
    content = None
    if cmd == "off":
        content = "display-off"
    elif cmd == "on":
        content = "display-on"
    if content:
        cancel_delayed_shutdown()
        logger.info("Broadcasting display status: %s", content)
        publish_ws("shutdown", content)
Exemple #14
0
    def handle(self, *args, **options):
        status = huawei_b593_status.HuaweiStatus()
        data = status.read()
        age_threshold = datetime.timedelta(minutes=2)

        try:
            latest_data = Internet.objects.latest()
            if now() - latest_data.timestamp > age_threshold:
                latest_data = Internet()
        except Internet.DoesNotExist:
            latest_data = Internet()

        latest_data.wifi = data["WIFI"] != "off"
        latest_data.signal = int(data["SIG"])
        latest_data.mode = data["Mode"]
        latest_data.sim = data["SIM"]
        latest_data.connect_status = data["Connect"]
        latest_data.update_timestamp = now()
        latest_data.save()
        publish_ws("internet", get_latest_serialized())
Exemple #15
0
 def post(self, request, *args, **kwargs):
     status = sp.is_alive()
     sp.shutdown()
     redis_instance.setex("server_power_in_progress", 60, status)
     publish_ws("server_power", {"status": status, "in_progress": status})
     return HttpResponse("ok")
Exemple #16
0
def publish_timer_deleted(sender, instance, using, **kwargs):
    publish_ws("timer-%s" % instance.pk, "delete")
Exemple #17
0
def publish_lightgroup_saved(sender, instance, *args, **kwargs):
    publish_ws("lightcontrol", get_serialized_lightgroups())
Exemple #18
0
 def post(self, request, *args, **kwargs):
     publish_ws("rdio-control", kwargs)
Exemple #19
0
def publish_changes():
    publish_ws("timer-labels", get_labels())
Exemple #20
0
def publish_items():
    publish_ws("printer-labels", json.loads(get_serialized_labels()))
Exemple #21
0
def publish_changes():
    for k in ("today", "tomorrow", "all"):
        publish_ws("repeating_tasks_%s" % k, get_repeating_data(k, True))
Exemple #22
0
def publish_changes():
    for k in ("today", "tomorrow", "all"):
        publish_ws("birthdays_%s" % k, get_birthdays(k))
Exemple #23
0
def publish_items():
    publish_ws("printer-labels", json.loads(get_serialized_labels()))
Exemple #24
0
def publish_timer_saved(sender, instance, created, *args, **kwargs):
    if created:
        publish_ws("timers", get_serialized_timer(instance))
    else:
        publish_ws("timer-%s" % instance.pk, get_serialized_timer(instance))
Exemple #25
0
def publish_lightautomation_saved(sender, instance, *args, **kwargs):
    publish_ws("lightcontrol_timed_%s" % instance.action, get_serialized_timed_action(instance))
Exemple #26
0
 def post(self, request, *args, **kwargs):
     publish_ws("rdio-control", kwargs)
Exemple #27
0
 def handle(self, *args, **options):
     publish_ws("reload", time.time())