CHEERSNetworkClimate & health

Home / Resources / Weather station

CHEERS technical resources · WindChaser

Source code for wind_bearer_software.remote_transfer_V1

WindChaser technical documentation: Source code for wind_bearer_software.remote_transfer_V1. Original instructions, component references and source limitations.

Original documentation: Min Tai Yap and Julian Walker · © 2025. Migrated to CHEERS on 3 December 2026. This is working documentation; unresolved source gaps remain visible.

Software source reference
"""
Script to send the collected data to a remote server.

Authors:
    Min Tai Yap
"""

import subprocess
import datetime
import os

# Auxiliary functions
from wind_bearer_software.utils.io_utils import read_parameter_dict



[docs] def scp_file(local_path, remote_path, server, ssh_key, user, log_file): """ Sends the file at local_path to the server with a prescpecified IPv4 address using the SCP protocol. If the transmission failed, the file path will be noted in the daily log fail. Upon successful transmission, it will try to resend each of the files in the daily log file. If this fails, it will leave the file in the log file. :param local_path: File to be transmitted :param remote_path: Path to the directory on the remote server where the transmitted file should be saved :param server: IPv4 address of the remote server :param ssh_key: Path to where the private SSH key is stored on the raspi :param user: Name of the user on the remote server :param log_file: Path to the daily log file :returns: True upon successful transmission of all files, otherwise False """ try: scp_command = f"scp -i {ssh_key} {local_path} {user}@{server}:{remote_path}" print(f"Executing command: {scp_command}") result = subprocess.run( scp_command, shell=True, check=True, capture_output=True, text=True ) # resend the files that are not successfully transferred previously failed_files = get_failed_transfers(log_file) if failed_files: print("Files that failed to transfer:") for file in failed_files: scp_command = f"scp -i {ssh_key} {file} {user}@{server}:{remote_path}" print(f"Executing command to transferred previous files: {scp_command}") try: result = subprocess.run( scp_command, shell=True, check=True, capture_output=True, text=True ) # remove the filename form the log file if trasnfer is successful if result.returncode == 0: remove_file_from_log(file, log_file) except subprocess.CalledProcessError as e: # Do not remove file from the log file if any errors happened during resending print(f"Transmission of {file} failed with error: {e.stderr.strip()}") print(f"Leaving {file} in {log_file}") else: print("No failed transfers logged.") return result.returncode == 0 # Return True if file transmission is successful except subprocess.CalledProcessError as e: print(f"File transmission failed with error: {e.stderr.strip()}") log_failed_transfer(local_path, log_file) # Log the failed transfer return False
# Error handling to resend failed transfer
[docs] def log_failed_transfer(file_name, log_file): # Logs the name of the file that failed to transfer into a text file. """ Logs the path of a file whose transmission failed in a log file. Ensures that each file is only mentioned once in the log file and creates a new log file if it doesn't exist yet. :param file_name: Path to the file whose transmission failed :param log_file: Path to the daily log file """ try: # Check if the file name already exists in the log file with open(log_file, 'r') as f: # Open in read mode existing_files = f.read().splitlines() # Read all lines, stripping newlines # If the file name is already in the log, do nothing if file_name in existing_files: print(f"'{file_name}' is already logged. Not adding again.") return # Append the new file name to the log file with open(log_file, 'a') as f: # Open in append mode f.write(f"{file_name}\n") print(f"Logged failed transfer: {file_name}") except FileNotFoundError: # If the log file doesn't exist, create it and log the filename with open(log_file, 'a') as f: f.write(f"{file_name}\n") print(f"Log file not found. Created new log file and logged: {file_name}") except Exception as e: print(f"Error logging failed transfer: {e}")
[docs] def get_failed_transfers(log_file): # Reads the log file and returns a list of failed file names. """ Fetches the file path of all the failed transmissions in the daily log file. :param log_file: Path to the daily log file :returns: A list of all failed transmissions noted in the daily log file """ try: with open(log_file, 'r') as f: # Open the log file in read mode failed_files = [line.strip() for line in f] # Read and strip whitespace return failed_files # Return the list of failed files except FileNotFoundError: print(f"No log file found: {log_file}") return [] # Return an empty list if the log file doesn't exist except Exception as e: print(f"Error reading log file: {e}") return [] # Handle other potential errors gracefully
[docs] def remove_file_from_log(filename, log_file): # Removes the given filename from the log file if it exists. """ Removes a successfully sent file from the log file. :param filename: Path to the file which was successfully resent :param log_file: Path to the log file """ try: # Read all lines from the log file with open(log_file, 'r') as fo: lines = fo.readlines() # Filter out the matching filename updated_lines = [line for line in lines if line.strip() != filename] # Write the updated content back to the log file with open(log_file, 'w') as fo: fo.writelines(updated_lines) if len(lines) == len(updated_lines): print(f"'{filename}' not found in the log file.") else: print(f"'{filename}' has been removed from the log file.") except FileNotFoundError: print(f"No log file found: {log_file}. Nothing to remove.") except Exception as e: print(f"Error processing the log file: {e}")
[docs] def main(): """ Sends the collected data to the remote server specified in parameter/remote_details.txt using the SCP protocol. It is assumed that this script is always called at the beginning of a new hour, and it transmits the csv assumed to be created exactly one hour ago. Furthermore, it is necessary that all parameters in the JSON files in the parameter directory are correctly set. Failed transmissions are logged in a daily log file. If the transmission of the data collected during the previous hour was successful, this script will also try to resend any unsent files logged in the daily log file. """ # Get current date in ddmmyyyy format today = datetime.datetime.now() # Format today's date as "ddmmyyyy" today_str = datetime.datetime.now().strftime("%d%m%Y") # Get yesterday's date by subtracting one day yesterday = today - datetime.timedelta(days=1) # Format yesterday's date as "ddmmyyyy" yesterday_str = yesterday.strftime("%d%m%Y") # Get the current hour as an integer current_hour = int(datetime.datetime.now().strftime('%H')) print(f"current hour: {current_hour}") # Calculate the previous hour using modulo arithmetic previous_hour = int((current_hour - 1) % 24) previous_hour = str(previous_hour).zfill(2) # Zero-pad single digits so that it will be two digits all the time print(f"previous hour: {previous_hour}") # User parameters param_dict = read_parameter_dict('parameters.json') ws_name = param_dict["ws_name"] # File path file_path_dict = read_parameter_dict('user_path.json') local_saved_dir = file_path_dict['local_ds'] saved_dirs = file_path_dict['ds'] # Server details rd_dict = read_parameter_dict('remote_details.json') user = rd_dict["rs_name"] server = rd_dict["rs_address"] remote_dir = rd_dict["rs_dir"] ssh_key_private = rd_dict["ssh_key_private"] ssh_key_public = rd_dict["ssh_key_public"] # Get paths & directories for folder_path in saved_dirs: if os.path.exists(folder_path): log_path = folder_path # initialising the log_file print(f"log_path: {log_path}") current_date = datetime.datetime.now().strftime('%d%m%Y') log_path_new = f"{current_date}_data" log_path_new = os.path.join(log_path, log_path_new) log_name = f"{current_date}_missed_transfer.log" log_file = os.path.join(log_path_new, log_name) # Check current date, if current hour is 00 means should send yesterday data at 23, else just send previous hour data of current day if current_hour == 0: local_file = f"{local_saved_dir}/{yesterday_str}_data/{ws_name}_{yesterday_str}_{previous_hour}.csv" print(f"Transferring {local_file}") else: local_file = f"{local_saved_dir}/{today_str}_data/{ws_name}_{today_str}_{previous_hour}.csv" print(f"Transferring {local_file}") # Establish connection and remote transmission if scp_file(local_file, remote_dir, server, ssh_key_private, user, log_file): print("File transmission successful.") else: print("File transmission failed.")
if __name__ == "__main__": main()