{"id":18174643,"url":"https://github.com/sourceduty/power-input_log","last_synced_at":"2025-04-07T09:29:53.122Z","repository":{"id":252988388,"uuid":"842118747","full_name":"sourceduty/Power-Input_Log","owner":"sourceduty","description":"💻 Log the total time a computer is powered on, and the time spent inputting or idling while powered on. ","archived":false,"fork":false,"pushed_at":"2024-11-01T19:19:47.000Z","size":19,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-11-09T16:46:16.379Z","etag":null,"topics":["c-plus-plus","computer-usage","computer-user","idea","linux","log","logger","logging","macos","power-input","power-input-log","power-log","power-logger","programming","statistics","usage-log","user-log","windows"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sourceduty.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-08-13T17:53:18.000Z","updated_at":"2024-11-01T19:19:51.000Z","dependencies_parsed_at":"2024-08-13T21:27:48.229Z","dependency_job_id":null,"html_url":"https://github.com/sourceduty/Power-Input_Log","commit_stats":null,"previous_names":["sourceduty/power-input_log"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sourceduty%2FPower-Input_Log","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sourceduty%2FPower-Input_Log/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sourceduty%2FPower-Input_Log/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sourceduty%2FPower-Input_Log/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sourceduty","download_url":"https://codeload.github.com/sourceduty/Power-Input_Log/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":230650375,"owners_count":18259281,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["c-plus-plus","computer-usage","computer-user","idea","linux","log","logger","logging","macos","power-input","power-input-log","power-log","power-logger","programming","statistics","usage-log","user-log","windows"],"created_at":"2024-11-02T16:07:02.238Z","updated_at":"2024-12-20T21:43:00.113Z","avatar_url":"https://github.com/sourceduty.png","language":null,"readme":"![Power-Input Log](https://github.com/user-attachments/assets/43ab8965-d390-47aa-8b8b-6acb73fc313a)\n\n\u003e Log the total time a computer is powered on, and the time spent inputting or idling while powered on.\n\n#\n\nThe Power-Input Log is a system feature designed to record and analyze the usage patterns of a computer. Specifically, it tracks the total time a computer is powered on and the time actively spent inputting (via keyboard or mouse) while powered on. The feature aims to provide insights into the operational efficiency of a computer by calculating the total running time from the purchase date, total idle time (powered on but unused), and the total active input time.\n\nThe Power-Input Log works by starting a timer each time the computer is powered on. Simultaneously, it monitors user input activity through keyboard and mouse events. When the computer is idle, with no input detected for a predefined period, the system notes this as idle time. The total running time is calculated from the moment the system is first powered on after purchase and continues to accumulate until the system is powered off.\n\nTo effectively calculate these metrics, the system maintains logs that timestamp when the computer is turned on and off, and when input activity is detected or stops. These logs are then processed to compute the total active and idle times. The Power-Input Log will periodically update these metrics and store them for users to review. This feature can be especially useful for both personal and enterprise environments to monitor device usage and optimize power management strategies.\n\nIncorporating the Power-Input Log into Windows 11 will involve utilizing system APIs to detect power state changes and input events, and then storing this data in a local database or log file. Users can access a simple interface that displays their computer's total running time since purchase, active input time, and idle time. This feature can also include options for exporting the log data for further analysis.\n\n#\n\n\u003cdetails\u003e\u003csummary\u003ePython Concepts\u003c/summary\u003e\n\u003cbr\u003e\n\n```\nimport time\n\nimport datetime\nimport os\nimport json\nfrom pynput import keyboard, mouse\n\n# Define file path for saving logs\nlog_file_path = os.path.join(os.getenv('USERPROFILE'), 'power_input_log.json')\n\n# Load or initialize log data\nif os.path.exists(log_file_path):\n    with open(log_file_path, 'r') as file:\n        log_data = json.load(file)\nelse:\n    log_data = {\n        \"purchase_date\": str(datetime.datetime.now()),\n        \"power_on_times\": [],\n        \"input_times\": []\n    }\n\n# Function to calculate time differences\ndef calculate_time_diff(start_time, end_time):\n    delta = end_time - start_time\n    return delta.total_seconds()\n\n# Function to update log data\ndef update_log():\n    with open(log_file_path, 'w') as file:\n        json.dump(log_data, file)\n\n# Event handlers for power and input monitoring\ndef on_power_on():\n    log_data['power_on_times'].append({\n        \"start_time\": str(datetime.datetime.now()),\n        \"end_time\": None\n    })\n    update_log()\n\ndef on_power_off():\n    if log_data['power_on_times'] and log_data['power_on_times'][-1]['end_time'] is None:\n        log_data['power_on_times'][-1]['end_time'] = str(datetime.datetime.now())\n        update_log()\n\ndef on_input():\n    if not log_data['input_times'] or (log_data['input_times'][-1]['end_time'] is not None):\n        log_data['input_times'].append({\n            \"start_time\": str(datetime.datetime.now()),\n            \"end_time\": None\n        })\n    update_log()\n\ndef on_input_end():\n    if log_data['input_times'] and log_data['input_times'][-1]['end_time'] is None:\n        log_data['input_times'][-1]['end_time'] = str(datetime.datetime.now())\n        update_log()\n\n# Start monitoring power on event\non_power_on()\n\n# Monitor keyboard and mouse events\nkeyboard_listener = keyboard.Listener(on_press=on_input, on_release=on_input_end)\nmouse_listener = mouse.Listener(on_move=on_input, on_click=on_input, on_scroll=on_input)\n\nkeyboard_listener.start()\nmouse_listener.start()\n\n# Keep the script running\ntry:\n    while True:\n        time.sleep(1)\nexcept KeyboardInterrupt:\n    on_power_off()\n    print(\"Script terminated by user.\")\n    update_log()\n\n# Calculate total running, active, and idle time\ndef calculate_statistics():\n    total_running_time = 0\n    total_active_input_time = 0\n    for power_session in log_data['power_on_times']:\n        start_time = datetime.datetime.fromisoformat(power_session['start_time'])\n        end_time = datetime.datetime.fromisoformat(power_session['end_time']) if power_session['end_time'] else datetime.datetime.now()\n        total_running_time += calculate_time_diff(start_time, end_time)\n    \n    for input_session in log_data['input_times']:\n        start_time = datetime.datetime.fromisoformat(input_session['start_time'])\n        end_time = datetime.datetime.fromisoformat(input_session['end_time']) if input_session['end_time'] else datetime.datetime.now()\n        total_active_input_time += calculate_time_diff(start_time, end_time)\n    \n    total_idle_time = total_running_time - total_active_input_time\n    print(f\"Total running time (in seconds): {total_running_time}\")\n    print(f\"Total active input time (in seconds): {total_active_input_time}\")\n    print(f\"Total idle time (in seconds): {total_idle_time}\")\n\ncalculate_statistics()\n```\n\nThis Python script is a basic implementation of the Power-Input Log feature for Windows 11. It tracks when the computer is powered on and monitors input activities using the pynput library. The script logs these activities and calculates total running time, active input time, and idle time. Note that additional error handling and integration with Windows-specific power events (like sleep, hibernate) would be necessary for a production environment.\n\n\u003cbr\u003e\n\u003c/details\u003e\n\u003cdetails\u003e\u003csummary\u003eC++ Concept (Data-Time Log)\u003c/summary\u003e\n\u003cbr\u003e\n\n```\n#include \u003ciostream\u003e\n#include \u003cfstream\u003e\n#include \u003cwindows.h\u003e\n#include \u003cchrono\u003e\n#include \u003ciomanip\u003e\n#include \u003csstream\u003e\n#include \u003cthread\u003e\n\n// Function to get the current date-time as a formatted string\nstd::string getCurrentDateTime() {\n    auto now = std::chrono::system_clock::now();\n    std::time_t now_c = std::chrono::system_clock::to_time_t(now);\n    std::stringstream ss;\n    ss \u003c\u003c std::put_time(std::localtime(\u0026now_c), \"%Y-%m-%d %H:%M:%S\");\n    return ss.str();\n}\n\n// Function to get the system's idle time in milliseconds\nDWORD getIdleTime() {\n    LASTINPUTINFO lii;\n    lii.cbSize = sizeof(LASTINPUTINFO);\n    GetLastInputInfo(\u0026lii);\n    return (GetTickCount() - lii.dwTime);\n}\n\n// Function to log data to file with timestamps\nvoid logToFile(const std::string\u0026 state, const std::string\u0026 startTime, const std::string\u0026 endTime, double duration) {\n    std::ofstream logFile(\"power_input_log.json\", std::ios::app);\n    if (logFile.is_open()) {\n        logFile \u003c\u003c \"{\\n\";\n        logFile \u003c\u003c \"  \\\"state\\\": \\\"\" \u003c\u003c state \u003c\u003c \"\\\",\\n\";\n        logFile \u003c\u003c \"  \\\"start_time\\\": \\\"\" \u003c\u003c startTime \u003c\u003c \"\\\",\\n\";\n        logFile \u003c\u003c \"  \\\"end_time\\\": \\\"\" \u003c\u003c endTime \u003c\u003c \"\\\",\\n\";\n        logFile \u003c\u003c \"  \\\"duration_seconds\\\": \" \u003c\u003c duration \u003c\u003c \"\\n\";\n        logFile \u003c\u003c \"},\\n\";\n        logFile.close();\n    } else {\n        std::cerr \u003c\u003c \"Unable to open log file.\\n\";\n    }\n}\n\nint main() {\n    const DWORD idleThreshold = 5000; // 5 seconds threshold for idle detection\n    std::string currentState = \"active\";\n    std::string startTime = getCurrentDateTime();\n    \n    while (true) {\n        DWORD idleTime = getIdleTime();\n        std::string newState = (idleTime \u003c idleThreshold) ? \"active\" : \"idle\";\n\n        // Check if state has changed from active to idle or vice versa\n        if (newState != currentState) {\n            std::string endTime = getCurrentDateTime();\n            auto duration = std::chrono::duration\u003cdouble\u003e(std::chrono::system_clock::now() - std::chrono::system_clock::from_time_t(std::time(0)));\n            logToFile(currentState, startTime, endTime, duration.count());\n            \n            // Update state and start time for new period\n            currentState = newState;\n            startTime = endTime;\n        }\n\n        // Add a delay to reduce CPU usage\n        std::this_thread::sleep_for(std::chrono::seconds(1));\n\n        // Optional: Stop the program after a set duration for testing purposes\n        // This example runs for 1 minute (use this to limit the test duration)\n        auto programEndTime = std::chrono::steady_clock::now() + std::chrono::minutes(1);\n        if (std::chrono::steady_clock::now() \u003e= programEndTime) {\n            break;\n        }\n    }\n\n    return 0;\n}\n```\n\nThe Date-Time Log program developed in C++ serves as a precise tracking tool for monitoring active and idle times on a Windows computer. By leveraging the Windows API, it captures system idle periods based on user input inactivity and transitions between states, logging each active or idle period with exact timestamps. This allows it to accurately record the start and end times of each activity state, along with the duration in seconds. By outputting data in JSON format, the program provides structured and accessible logs that include details like the state (active or idle), start time, end time, and total duration. This level of logging is ideal for applications that require accurate monitoring of system usage, such as user behavior analysis, productivity tracking, or power management optimization.\n\nThe program utilizes the \u003cchrono\u003e library to manage high-resolution time data, offering a reliable and cross-platform compatible method for date and time manipulation. The result is a user-friendly, efficient, and low-resource logging tool that runs continuously, only pausing when the system state changes. With adjustable idle thresholds and easy customization for different logging intervals, this program is a versatile solution for tracking computer usage. Additionally, the JSON log format facilitates easy integration into analytics tools or databases, making it simple for users to perform further analysis or visualization on the data. The program’s implementation as a standalone .exe makes it convenient for deployment on any Windows system, providing both personal users and enterprises with a powerful way to optimize their device usage.\n\n\u003cbr\u003e\n\u003c/details\u003e\n\n#\n### Related Links\n\n[ChatGPT](https://github.com/sourceduty/ChatGPT)\n\u003cbr\u003e\n[Power-Time Log](https://github.com/sourceduty/Power-Time_Logger)\n\n***\nCopyright (C) 2024, Sourceduty - All Rights Reserved.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsourceduty%2Fpower-input_log","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsourceduty%2Fpower-input_log","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsourceduty%2Fpower-input_log/lists"}