예제 #1
0
def take_best_picture_remembering(app_cfg, system, machine_cfg):
    machine_key = machine_cfg.display_name

    Console.WriteLine("-------------------------------------------------")

    Console.WriteLine("[{0}] Taking the best pic ever for {1} ({2})",
                      datetime.today().strftime("%Y-%m-%d %H:%M:%S"),
                      machine_key, machine_cfg.name)

    current = system.take_best_picture_ever(machine_cfg)

    takenTime = datetime.today()
    filename = takenTime.strftime("%Y-%m-%d_%H.%M.%S")
    path_final = path_cropped.format(app_cfg.root_path, machine_key.lower(),
                                     filename)

    Console.WriteLine("[{0}] Finished because {1}: {2}",
                      datetime.today().strftime("%Y-%m-%d %H:%M:%S"),
                      system.last_stopped_reason, path_final)

    if machine_cfg.must_save_full_pic:
        full_image_path = path_full_photo.format(app_cfg.root_path,
                                                 machine_key, filename,
                                                 int(current.shutter_speed),
                                                 system.last_count,
                                                 system.last_stopped_reason)
        open(full_image_path, 'wb').write(current.img.read())
        Console.WriteLine("saved")
        current.img.seek(0)
    img = Image.open(current.img)
    img.crop((machine_cfg.picture_left_margin, machine_cfg.picture_top_margin,
              machine_cfg.picture_left_margin + machine_cfg.picture_width,
              machine_cfg.picture_top_margin +
              machine_cfg.picture_height)).save(path_final)
    url = url_ws + '/api/upload'
    files = {"form_input_field_name1": open(path_final, "rb")}
    requests.post(url, files=files)

    hqurl = "{0}/api/machines/picture/upload".format(app_cfg.url_hq)
    headers = {
        "HqTakerName": app_cfg.taker_name,
        "HqApiKey": app_cfg.api_key,
        "HqIdMachine": str(machine_cfg.id),
        "HqTakenTime": takenTime.strftime("%Y-%m-%d %H:%M:%S"),
    }
    files = {"form_input_field_name1": open(path_final, "rb")}
    requests.post(hqurl, files=files, headers=headers)
    os.remove(path_final)
예제 #2
0
def get_config(app_cfg):
    Console.WriteLine("[{0}] Get config from WS",
                      datetime.today().strftime("%Y-%m-%d %H:%M:%S"))
    hqurl = "{0}/api/machines/config/list/{1}/{2}".format(
        app_cfg.url_hq, app_cfg.taker_name, app_cfg.api_key)
    hq_cfg = requests.get(hqurl).json()
    return HqConfig(hq_cfg)
예제 #3
0
from datetime import datetime
import sys
import io
import json
import os

import RPi.GPIO as GPIO
import time
import urllib2

from util import Console
from configs import AppConfig

config_path = "/config/hvac_switch.cfg"

Console.WriteLine("")
Console.WriteLine("#######################################################")
Console.WriteLine("#######################################################")
app_config = None

with open(config_path, 'r') as content_file:
    j = json.loads(content_file.read())
    app_config = AppConfig(j)

Console.WriteLine("[{0}] Taking control of gpios",
                  datetime.today().strftime("%Y-%m-%d %H:%M:%S"))
GPIO.setmode(GPIO.BCM)

GPIO.setup(app_config.pin_on, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(app_config.pin_off, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    def take_best_picture_ever(self, machine_cfg):
        machine_key = machine_cfg.display_name
        self.camera.rotation = machine_cfg.photo_rotation
        last_photoshoot = None
        if os.path.isfile(
                path_last_config.format(self.app_config.root_path,
                                        machine_key)):
            with open(
                    path_last_config.format(self.app_config.root_path,
                                            machine_key), 'r') as content_file:
                j = json.loads(content_file.read())
                last_photoshoot = PictureConfig(j["shutter_speed"],
                                                j["brightness"], j["delta"])

        current = None
        last = None
        checkpoint = None
        closest = None

        ss = 2 if last_photoshoot is None else last_photoshoot.shutter_speed
        self.last_count = 0
        tested_under = False
        tested_over = False
        self.last_stopped_reason = "unknown"

        while ss > 0 and ss <= machine_cfg.max_ss and self.last_count < machine_cfg.max_try and (
                current is None or current.delta > machine_cfg.accepted_delta):
            self.last_count += 1
            try:
                current = TakenPicture(ss, self.take_picture_stream(int(ss)),
                                       machine_cfg)
                Console.WriteLine("br={0} accepted_delta={2} curr_delta={1}",
                                  current.brightness, current.delta,
                                  machine_cfg.accepted_delta)

                if current.brightness < machine_cfg.ideal_brightness:
                    Console.DebugLine("UNDER: CHECK")
                    tested_under = True

                if current.brightness > machine_cfg.ideal_brightness:
                    Console.DebugLine("OVER: CHECK")
                    tested_over = True

                if closest is None or current.delta < closest.delta:
                    Console.DebugLine("CLOSEST YET")
                    closest = current

                if current.delta < machine_cfg.accepted_delta:
                    Console.DebugLine("OK ! FINISH")
                    self.last_stopped_reason = "accepted"
                    break

                if ss == machine_cfg.max_ss and current.brightness < machine_cfg.ideal_brightness:
                    Console.DebugLine("EXPLODE")
                    self.last_stopped_reason = "max_ss"
                    break

                if ss == 1 and current.brightness > machine_cfg.ideal_brightness:
                    self.last_stopped_reason = "min_ss"
                    Console.DebugLine("DIE")
                    break

                if not tested_over:
                    checkpoint = current
                    multiplier = min(10, max(2, current.delta / 10))
                    Console.DebugLine("EXCESSIVE PUSH * {0}, CP = CUR",
                                      multiplier)
                    ss *= multiplier
                elif not tested_under:
                    checkpoint = current
                    divider = min(10, max(2, current.delta / 10))
                    Console.DebugLine("EXCESSIVE CALM DOWN / {0}, CP = CUR",
                                      divider)
                    ss /= divider
                else:
                    if ss > last.shutter_speed and current.brightness > machine_cfg.ideal_brightness:
                        Console.DebugLine("CP = LAST")
                        checkpoint = last
                    elif ss < last.shutter_speed and current.brightness < machine_cfg.ideal_brightness:
                        Console.DebugLine("CP = LAST")
                        checkpoint = last

                    pct = 100 * current.delta / \
                        (current.delta + checkpoint.delta)
                    diff_ss = abs(ss - checkpoint.shutter_speed)

                    if current.brightness > machine_cfg.ideal_brightness:
                        Console.DebugLine(
                            "CONCENTRATE BACKWARD {0:.04f}% of {1}", pct,
                            diff_ss)
                        ss -= pct * (diff_ss) / 100
                    else:
                        Console.DebugLine(
                            "CONCENTRATE FORWARD {0:.04f}% of {1}", pct,
                            diff_ss)
                        ss += pct * (diff_ss) / 100

                if self.last_count == machine_cfg.max_try:
                    Console.DebugLine("ENOUGH")
                    self.last_stopped_reason = "max_tries"
                    break

                if ss > machine_cfg.max_ss:
                    Console.DebugLine("JUST BELOW EXPLOSION")
                    ss = machine_cfg.max_ss

                if ss < 1:
                    Console.DebugLine("JUST ABOVE DEATH")
                    ss = 1

                if int(ss) == int(current.shutter_speed):
                    self.last_stopped_reason = "closest"
                    break

                last = current
                current = None

            except Exception as inst:
                Console.WriteLine("")
                print("Unexpected error:", sys.exc_info()[0])
                print(type(inst))  # the exception instance
                print(inst.args)  # arguments stored in .args
                print(inst)
                traceback.print_exc()
                break

        current.img.seek(0)

        cfg = open(
            path_last_config.format(self.app_config.root_path, machine_key),
            "w")
        cfg.write(
            json.dumps(
                {
                    'shutter_speed': current.shutter_speed,
                    'brightness': current.brightness,
                    'delta': current.delta,
                    'stopped_reason': self.last_stopped_reason
                },
                sort_keys=True,
                indent=4,
                separators=(',', ': ')))
        cfg.close()

        return current
예제 #5
0
    }
    files = {"form_input_field_name1": open(path_final, "rb")}
    requests.post(hqurl, files=files, headers=headers)
    os.remove(path_final)


def get_config(app_cfg):
    Console.WriteLine("[{0}] Get config from WS",
                      datetime.today().strftime("%Y-%m-%d %H:%M:%S"))
    hqurl = "{0}/api/machines/config/list/{1}/{2}".format(
        app_cfg.url_hq, app_cfg.taker_name, app_cfg.api_key)
    hq_cfg = requests.get(hqurl).json()
    return HqConfig(hq_cfg)


Console.WriteLine("")
Console.WriteLine("#######################################################")
Console.WriteLine("#######################################################")
app_config = None
try:
    with open(config_path, 'r') as content_file:
        j = json.loads(content_file.read())
        app_config = AppConfig(j)

    Console.WriteLine("[{0}] Taking control of camera",
                      datetime.today().strftime("%Y-%m-%d %H:%M:%S"))
    camera = PiCamera(resolution=(2592, 1944))
    try:
        system = ImagingSystem(camera, app_config)
        Console.WriteLine("[{0}] Init camera parameters",
                          datetime.today().strftime("%Y-%m-%d %H:%M:%S"))