Ejemplo n.º 1
0
def get_temperature():
    data = {}
    cpu_temp = util.get_cpu_temperature()
    temps = cpu_temps[1:] + [cpu_temp]
    avg_cpu_temp = sum(temps) / float(len(temps))
    raw_temp = tph.get_temperature()
    adj_temp = raw_temp - ((avg_cpu_temp - raw_temp) / cfg.factor)
    data["temperature_cpu"] = cpu_temp
    data["temperature"] = raw_temp
    data["temperature_adj"] = adj_temp
    return data
Ejemplo n.º 2
0
def get_temperature():
    data = {}
    cpu_temp = util.get_cpu_temperature()
    temps = cpu_temps[1:] + [cpu_temp]
    avg_cpu_temp = sum(temps) / float(len(temps))
    raw_temp = sense.get_temperature()
    adj_temp = raw_temp - ((avg_cpu_temp - raw_temp) / cfg.factor)
    data["temperature_cpu"] = cpu_temp
    data["temperature"] = raw_temp
    data["temperature_adj"] = adj_temp

    #data["temperature"] = sense.get_temperature()
    data["temperature_humidity"] = sense.get_temperature_from_humidity()
    data["temperature_pressure"] = sense.get_temperature_from_pressure()
    return data
Ejemplo n.º 3
0
def _loop_recoder():
    global _cfg
    global _stop
    global _VIDEO_WIDTH
    global _VIDEO_HEIGHT
    global n_loops
    global current_record_name
    global last_recorded_name
    global recording_on
    global recording_status_text

    try:
        camera = None
        recording_status_text = "Initializing Pi Camera to {0}x{1} @ {2} fps".format(
            _VIDEO_WIDTH, _VIDEO_HEIGHT, config.VIDEO_FPS)
        logger.info(recording_status_text)
        _update_subs_on_status(recording_status_text)

        # Initialize camera
        camera = picamera.PiCamera()
        camera.resolution = (_VIDEO_WIDTH, _VIDEO_HEIGHT)
        camera.framerate_range = (1, config.VIDEO_FPS)
        camera.framerate = config.VIDEO_FPS
        camera.annotate_background = True
        fixed_annotation = "RavikiranB.com"
        camera.annotate_text_size = config.ANNOTATE_TEXT_SIZE
        current_rotation = _cfg[CFG_ROT_KEY]
        camera.rotation = current_rotation

        location_text = None

        index = _cfg[CFG_CURR_INDEX_KEY] + 1
        n_loops = _cfg[CFG_N_LOOPS_KEY]

        recording_status_text = "Starting Recording."
        _update_subs_on_status(recording_status_text)

        #webinterface.WebInterfaceHandler.program_start_time = datetime.now()
        high_temp_triggered = False

        recording_on = True

        while not _stop:
            try:
                disk_used_space_percent = get_disk_space_info()

                if _cfg[CFG_MAX_FILES_KEY] == 0:
                    if (disk_used_space_percent >=
                            config.MAX_USED_DISK_SPACE_PERCENT):
                        # From now on recording index will loop
                        # back to zero when index
                        # reaches _cfg[CFG_MAX_FILES_KEY]
                        _cfg[CFG_MAX_FILES_KEY] = index
                        index = 0
                        n_loops += 1
                        _cfg[CFG_N_LOOPS_KEY] = n_loops
                elif index >= _cfg[CFG_MAX_FILES_KEY]:
                    index = 0
                    n_loops += 1
                    _cfg[CFG_N_LOOPS_KEY] = n_loops

                # Update SoC temperature in video annotation, to keep
                # track of resolution drop vs temp.
                cpu_temp = util.get_cpu_temperature()
                if cpu_temp >= config.TEMPERATURE_THRESHOLD_HIGH:
                    if not high_temp_triggered:
                        logger.warning(
                            "CPU temperature %s C exceeded threshold %s C",
                            cpu_temp, config.TEMPERATURE_THRESHOLD_HIGH)
                        logger.warning("Reducing video resolution")
                        _VIDEO_WIDTH = config.LOW_RES_VIDEO_WIDTH
                        _VIDEO_HEIGHT = config.LOW_RES_VIDEO_HEIGHT
                        camera.resolution = (_VIDEO_WIDTH, _VIDEO_HEIGHT)
                        high_temp_triggered = True
                elif cpu_temp <= config.TEMPERATURE_THRESHOLD_NORMAL:
                    if high_temp_triggered:
                        logger.warning("Restoring high video resolution")
                        _VIDEO_WIDTH = config.HIGH_RES_VIDEO_WIDTH
                        _VIDEO_HEIGHT = config.HIGH_RES_VIDEO_HEIGHT
                        camera.resolution = (_VIDEO_WIDTH, _VIDEO_HEIGHT)
                        high_temp_triggered = False

                _update_subs_on_cpu_temp(cpu_temp)

                # Record file name format: index_yyyy-mm-dd_HH-MM-SS.mp4
                rec_index = str(index)
                rec_time = _build_timestamp(forfile=False)
                rec_filename = (rec_index + '_' + _build_timestamp() +
                                config.RECORD_FORMAT_EXTENSION)
                rec_filepath = config.RECORDS_LOCATION + '/' + rec_filename

                video_format_text = "RPi DashCam {0}x{1} @ {2}fps".format(
                    _VIDEO_WIDTH, _VIDEO_HEIGHT, config.VIDEO_FPS)

                _cfg[CFG_CURR_INDEX_KEY] = index
                _cfg_save()

                # Delete old record with same index number,
                # Note: old record will have different time stamp on it.
                existing_records = glob.glob(config.RECORDS_LOCATION + '/' +
                                             rec_index + '_*')
                # There should be only one old record.
                for record in existing_records:
                    os.remove(record)

                mp4wfile = mp4writer.MP4Writer(filepath=rec_filepath,
                                               fps=config.VIDEO_FPS)

                # Uncomment the below call to record directly to the
                # underlying stdin object.
                #camera.start_recording(mp4wfile.get_file_object(),
                #                format='h264', quality=config.VIDEO_QUALITY)

                # Or use queue mechanism of mp4writer, this will
                # need more memory but no frame drops at higher resolutions.
                camera.start_recording(mp4wfile,
                                       format='h264',
                                       quality=config.VIDEO_QUALITY)

                current_record_name = rec_filename

                if high_temp_triggered:
                    recording_status_text = "Temperature exceeded {0}&deg;C, " \
                                    " video resolution reduced to {1}x{2}. " \
                                    "High resolution will be restored after temperature drops " \
                                    "below {3}&deg;C".format(
                                    config.TEMPERATURE_THRESHOLD_HIGH,
                                    _VIDEO_WIDTH,
                                    _VIDEO_HEIGHT,
                                    config.TEMPERATURE_THRESHOLD_NORMAL)
                else:
                    recording_status_text = "All OK"

                _update_subs_on_status(recording_status_text)

                seconds = 0
                while (not _stop) and (seconds < config.DURATION_SEC):
                    # update time
                    rec_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                    camera.annotate_text = (rec_index + ' - ' + rec_time +
                                            ' - ' + 'T ' + str(cpu_temp) +
                                            'C - ' + video_format_text +
                                            ' - ' + fixed_annotation)

                    if location_text:
                        camera.annotate_text += '\n' + location_text

                    # poll for any recorder related commands
                    try:
                        request = _cmd_q.get(block=False)
                        if request.cmd == Command.CMD_ROTATE:
                            current_rotation += 90
                            if current_rotation >= 360:
                                current_rotation = 0
                            camera.rotation = current_rotation
                            _cfg[CFG_ROT_KEY] = current_rotation
                            _cfg_save()
                            request.done()
                        elif request.cmd == Command.CMD_TAKE_LIVE_SNAPSHOT:
                            camera.capture(config.LIVESNAP_FILE,
                                           use_video_port=True)
                            request.done()
                        elif request.cmd == Command.CMD_SET_LOCATION_SPEED:
                            location_text = str(request.data)
                            request.done()
                    except queue.Empty:
                        pass

                    camera.wait_recording(1)
                    seconds += 1

                camera.stop_recording()

                mp4wfile.close()

                last_recorded_name = rec_filename

                index += 1

            except Exception as e:
                logger.error(traceback.format_exc())
                logger.error(e)
                logger.error('Recording Stopped')
                recording_status_text = "Internal error. Recording Stopped.<br>" + str(
                    e)
                _update_subs_on_status(recording_status_text)
                break

        recording_on = False
        if _stop:
            recording_status_text = "Recording stopped by user at " \
                        "{0}. Camera closed.".format(
                                _build_timestamp(forfile=False))

            _update_subs_on_status(recording_status_text)
    except Exception as e:
        logger.error(traceback.format_exc())
        logger.error(e)
        recording_status_text = "Internal error.<br>" + str(e)
        _update_subs_on_status(recording_status_text)
    finally:
        if camera:
            camera.close()
Ejemplo n.º 4
0
        fg = [255, 0, 0]
    sense.show_message(temp, text_colour=fg)
    return


# ------------------------------------------------------------------------
# Main
# ------------------------------------------------------------------------

sense = SenseHat()
sense.low_light = True
sense.set_rotation(cfg.ledRotation)
sense.clear()

# Temperature
cpu_temps = [util.get_cpu_temperature()] * 5

iot_data = {}
iot_data_tph = {}
iot_data_accel = {}
iot_data_gyro = {}
iot_data_compass = {}

fh = util.open_data_file(dataFile)
fh_tph = util.open_data_file(dataFileTph)
fh_accel = util.open_data_file(dataFileAccel)
fh_gyro = util.open_data_file(dataFileGyro)
fh_compass = util.open_data_file(dataFileCompass)

sprite = Sprites()
Ejemplo n.º 5
0
    def home_page(self):
        # loads home.html page in memory and replace its
        # keywords with corresponding contents.
        self.send_response(_HTTP_STATUS_CODE_OK)
        self.send_header('Content-type', 'text/html')

        filepath = config.HOME + '/html/home.html'

        page = ''
        with open(filepath, 'r') as f:
            page = f.read()
        page = page.replace('_VERSION', str(config.SOFTWARE_VERSION))

        page = page.replace('_STATUS_TEXT', recorder.recording_status_text)

        # Update SoC temperature
        cpu_temp = util.get_cpu_temperature()
        page = page.replace('_STEMP', str(cpu_temp) + "&deg;C")

        # Caluclate program uptime not system.
        duration = datetime.now() - WebInterfaceHandler.program_start_time
        total_secs = int(duration.seconds)
        uptime = ''
        if total_secs >= _HOUR_SEC:
            hours = int(total_secs / _HOUR_SEC)
            total_secs = total_secs % _HOUR_SEC
            uptime += "{0} hours ".format(hours)
        if total_secs > _MINUTE_SEC:
            mins = int(total_secs / _MINUTE_SEC)
            total_secs = total_secs % _MINUTE_SEC
            uptime += "{0} mins ".format(mins)
        uptime += "{0} seconds ".format(total_secs)
        page = page.replace('_UPTIME', uptime)

        ssid, my_ip = util.get_wlan_info()
        page = page.replace('_WLAN_SSID', ssid)
        page = page.replace('_IP_ADDR', my_ip)
        disk_space_used_percent = recorder.get_disk_space_info()
        page = page.replace('_DISK_SPACE', str(disk_space_used_percent) + '%')
        page = page.replace('_N_LOOPS', str(recorder.n_loops))
        page = page.replace('_CURR_REC', str(recorder.current_record_name))

        if recorder.recording_on:
            page = page.replace('_STATUS_COLOR', "lightgreen")
        else:
            page = page.replace('_STATUS_COLOR', "orange")

        rec_control = '<a href="/start">Start Recording</a>'
        if recorder.recording_on:
            rec_control = '<a href="/stop">Stop Recording</a>'

        page = page.replace(
            '_WEB_COMMANDS',
            '<a href="view-records">View/Download Records</a>' +
            '<a href="/rotate">Rotate 90&deg; &#x21bb;</a>' + rec_control +
            '<a href="/reboot">Reboot</a>' +
            '<a href="/poweroff">Power Off</a>')

        page = page.replace('_LRV_FILE', recorder.last_recorded_name)

        self.send_header('Content-Length', str(len(page)))
        self.send_no_cache()
        self.end_headers()

        self.wfile.write(bytes(page, "utf8"))
Ejemplo n.º 6
0
    def home_page(self):
        self.send_response(_HTTP_STATUS_CODE_OK)
        self.send_header('Content-type', 'text/html')

        filepath = config.HOME + '/html/home.html'

        page = ''
        with open(filepath, 'r') as f:
            page = f.read()

        # Update SoC temperature

        cpu_temp = util.get_cpu_temperature()
        page = page.replace('_STEMP', str(cpu_temp) + "&deg;C")
        page = page.replace(
            '_STEMP_NORMAL',
            str(config.TEMPERATURE_THRESHOLD_NORMAL) + "&deg;C")
        page = page.replace('_STEMP_HIGH',
                            str(config.TEMPERATURE_THRESHOLD_HIGH) + "&deg;C")

        # Caluclate program uptime not system.
        duration = datetime.now() - WebInterfaceHandler.program_start_time
        total_secs = int(duration.seconds)
        uptime = ''
        if total_secs >= _HOUR_SEC:
            hours = int(total_secs / _HOUR_SEC)
            total_secs = total_secs % _HOUR_SEC
            uptime += "{0} hours ".format(hours)
        if total_secs > _MINUTE_SEC:
            mins = int(total_secs / _MINUTE_SEC)
            total_secs = total_secs % _MINUTE_SEC
            uptime += "{0} mins ".format(mins)
        uptime += "{0} seconds ".format(total_secs)
        page = page.replace('_UPTIME', uptime)

        ssid, my_ip = util.get_wlan_info()
        page = page.replace('_WLAN_SSID', ssid)
        page = page.replace('_IP_ADDR', my_ip)
        disk_space_used_percent = recorder.get_disk_space_info()
        page = page.replace('_DISK_SPACE', str(disk_space_used_percent) + '%')
        page = page.replace('_N_LOOPS', str(recorder.n_loops))
        page = page.replace('_CURR_REC', str(recorder.current_record_name))

        if recorder.recording_on:
            page = page.replace('_STATUS_COLOR', "lightgreen")
        else:
            page = page.replace('_STATUS_COLOR', "orange")

        rec_control = '<a href="/start">Start Recording</a>'
        if recorder.recording_on:
            rec_control = '<a href="/stop">Stop Recording</a>'

        page = page.replace('_REC_CONTROL', rec_control)

        rec_table_rows = ''
        serial_no = 0
        rec_files = glob.glob(config.RECORDS_LOCATION + '/*' +
                              config.RECORD_FORMAT_EXTENSION)
        rec_files.sort(key=os.path.getmtime, reverse=True)

        for record in rec_files:
            rec_filename = pathlib.Path(record).name
            serial_no += 1
            rec_table_rows += """
                     <tr>
                            <td>{0}</td>
                            <td><a href="get-record?f={1}">{2}</a></td>
                            <td><button class="pbutton" 
                                title="Play Record" 
                                onclick='play_rec("{3}");'>
                                &#9658;</button></td>
                     </tr>
                    """.format(serial_no, rec_filename, rec_filename,
                               rec_filename)

        page = page.replace('_REC_TABLE_ROWS', rec_table_rows)

        self.send_header('Content-Length', str(len(page)))
        self.send_no_cache()
        self.end_headers()

        self.wfile.write(bytes(page, "utf8"))