def main():
    """Main doc """

    gs.initPaths()
    camera_data = gs.CAMERA_SETTINGS.copy()

    #
    # Get camera ID
    #
    camera_id = raw_input("Enter camera id number:")
    camera_id = check_camera_index(camera_id)
    camera_data[gs.CAMERA_IDENTITY] = camera_id

    #
    # Get cellular company
    # Note:
    # This is not needed any more as the modem is started in the rc.local file using
    # the NetworkManager.
    #
    # cell_company = None
    # while cell_company not in CELL_COMPANIES:
    #     cell_company = raw_input("Enter cellular company {companies}:".format(companies=CELL_COMPANIES))
    # camera_data[CELL_COMPANY] = cell_company

    #
    # Save the camera settings.
    #
    CameraNetwork.save_camera_data(gs.GENERAL_SETTINGS_PATH,
                                   gs.CAPTURE_SETTINGS_PATH,
                                   camera_settings=camera_data,
                                   capture_settings=gs.CAPTURE_SETTINGS)
Exemple #2
0
    def __init__(self, controller, identity=None, offline=False, local_path=None, local_proxy=False):
        """
        Class that encapsulates the camera action.

        parameters:
        ===========
        """

        self._local_mode = local_path is not None
        self._local_proxy = local_proxy
        gs.initPaths(local_path)

        #
        # Sync the clock.
        # Not done in local mode.
        #
        if local_path is None:
            logging.info('Syncing time')
            sync_time()

        #
        # Verify/Create the path where captured data is stored
        #
        if not os.path.isdir(gs.CAPTURE_PATH):
            os.makedirs(gs.CAPTURE_PATH)

        #
        # Get the connection data from the settings server.
        #
        self.camera_settings, self.capture_settings = load_camera_data(
            gs.GENERAL_SETTINGS_PATH, gs.CAPTURE_SETTINGS_PATH
        )
        self.update_proxy_params()
        self.ctx = zmq.Context()

        #
        # Set up the MDPWorker
        #
        if identity == None:
            identity = str(self.camera_settings[gs.CAMERA_IDENTITY])
            if self._local_mode:
                identity = os.path.split(local_path)[1] + "L"

        super(Server, self).__init__(
            context=self.ctx,
            endpoint="tcp://{ip}:{proxy_port}".format(**self.proxy_params),
            hb_endpoint="tcp://{ip}:{hb_port}".format(**self.proxy_params),
            service=identity,
            endpoint_callback=self.endpoint_callback
        )

        self._offline = offline
        self.capture_state = False

        #
        # Start the upload thread.
        # Note:
        # I am using a separate thread for uploading in order to use an
        # upload queue. We had a problem where slow upload caused many upload
        # processes to start together and cause jamming in communication.
        #
        self.upload_queue = Queue.Queue()
        if not self._local_mode:
            self.upload_thread = thread.start_new_thread(upload_thread,
                                                         (self.upload_queue,))

        #
        # Tunneling related parameters.
        #
        self.tunnel_process = None
        self.tunnel_port = None

        #
        # link to the controller
        #
        self._controller = controller
## ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.##
"""
Clean memory of the odroid.

The script moves captured date to a backup folder. To remove
the backup folder (and clear the memory) use the ``--delete`` flag.
"""

import argparse
import CameraNetwork.global_settings as gs
import datetime
import os
import shutil
import warnings

gs.initPaths()

BACKUP_FOLDER = os.path.expanduser(
    datetime.datetime.now().strftime("~/BACKUP_%Y_%m_%d")
)


def move(src_path):

    _, tmp = os.path.split(src_path)
    dst_path = os.path.join(BACKUP_FOLDER, tmp)

    if not os.path.exists(src_path):
        print("Source path does not exist: {}".format(src_path))
        return
Exemple #4
0
def main():
    parser = argparse.ArgumentParser(
        description='Start the modem and setup the default tunnel')
    parser.add_argument('--skip_tunnel',
                        action='store_true',
                        help='Skip starting the default tunnel')
    parser.add_argument(
        '--log_level',
        default='DEBUG',
        help='Set the log level (possible values: info, debug, ...)')
    args = parser.parse_args()

    #
    # Initialize paths.
    #
    gs.initPaths()

    #
    # Initialize the logger
    #
    CameraNetwork.initialize_logger(log_path=gs.DEFAULT_LOG_FOLDER,
                                    log_level=args.log_level,
                                    postfix='_tunnel')

    #
    # Set the autossh debug environment variable
    #
    os.environ["AUTOSSH_DEBUG"] = "1"

    camera_settings, capture_settings = CameraNetwork.load_camera_data(
        gs.GENERAL_SETTINGS_PATH, gs.CAPTURE_SETTINGS_PATH)
    identity = str(camera_settings[gs.CAMERA_IDENTITY])

    #
    # Start the tunnel
    #
    if not args.skip_tunnel:
        logging.info('starting tunnel')

        #
        # Loop till network reached.
        #
        network_reached = False
        failures_cnt = 0
        while not network_reached:
            try:
                proxy_params = CameraNetwork.retrieve_proxy_parameters()
                network_reached = True
            except:
                #
                # There is probably some problem with the internet connection.
                #
                failures_cnt += 1

                if failures_cnt > camera_settings[gs.INTERNET_FAILURE_THRESH]:
                    logging.error('Failed to connect 3G modem. Will reboot...')
                    # TODO Long term fix
                    os.system(
                        'sync; sudo reboot -f'
                    )  # Changed from 'sudo reboot', workaround for reboot hanging

                logging.error(
                    'Failed to retrieve proxy parameters. will sleep and try again later.'
                )
                time.sleep(gs.WD_TEST_INTERNET_PERIOD)

        _, tunnel_port = CameraNetwork.setup_reverse_ssh_tunnel(**proxy_params)

        #
        # Upload the tunnel port to the proxy.
        #
        file_name = "tunnel_port_{}.txt".format(identity)

        with open(file_name, 'w') as f:
            json.dump({"password": "******", "tunnel_port": tunnel_port}, f)

        CameraNetwork.upload_file_to_proxy(src_path=os.path.abspath(file_name),
                                           dst_path=file_name,
                                           **proxy_params)

    #
    # Internet watchdog loop.
    #
    failures_cnt = 0
    while True:
        time.sleep(gs.WD_TEST_INTERNET_PERIOD)

        #
        # Check internet connection every 2 WD_TEST_INTERNET_PERIOD secs.
        # If fails for more than WS_INTERNET_FAILURE_TRHESH consecutive times,
        # do a restart of the system.
        #
        if not CameraNetwork.check_connection():
            failures_cnt += 1
            logging.debug('Internet watchdog: failure number: %d.' %
                          failures_cnt)
            if failures_cnt > camera_settings[gs.INTERNET_FAILURE_THRESH]:
                logging.error('Failed to connect 3G modem. Will reboot...')
                # TODO Long term fix
                os.system(
                    'sync; sudo reboot -f'
                )  # Changed from 'sudo reboot', workaround for reboot hanging
        else:
            logging.debug('Internet watchdog: succeed.')
            failures_cnt = 0
Exemple #5
0
    capture_settings[gs.DAY_SETTINGS][gs.LOOP_DELAY] = \
        capture_settings[gs.LOOP_DELAY]
    capture_settings[gs.NIGHT_SETTINGS][gs.LOOP_DELAY] = \
        gs.CAPTURE_SETTINGS[gs.NIGHT_SETTINGS][gs.LOOP_DELAY]

    del capture_settings[gs.LOOP_DELAY]

    #
    # Save the camera settings.
    #
    CameraNetwork.save_camera_data(gs.GENERAL_SETTINGS_PATH,
                                   gs.CAPTURE_SETTINGS_PATH,
                                   camera_settings=camera_settings,
                                   capture_settings=capture_settings)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Update the camera settings from old to new format.')
    parser.add_argument(
        '--local_path',
        type=str,
        default=None,
        help='If set, the script will use the given path as home folder.')
    args = parser.parse_args()

    gs.initPaths(args.local_path)

    main()
Exemple #6
0
def main():
    parser = argparse.ArgumentParser(description='Start the server application')
    parser.add_argument('--log_level', default='DEBUG', help='Set the log level (possible values: info, debug, ...)')
    parser.add_argument('--unloop', action='store_false', help='When set, the camera will not start in loop mode')
    parser.add_argument('--identity', type=str, default=None, help='ID of the server (defaults to the value in the camera settings).')
    parser.add_argument('--offline', action='store_true', help='When set, the server will work without camera nor shader. This setup is useful for offline running.')
    parser.add_argument('--local_path', type=str, default=None, help='If set, the camera will work in local and offline mode, using the given path as home.')
    parser.add_argument('--local_proxy', action='store_true', help='When set, the server will work against a local proxy. This setup is useful for offline running.')
    args = parser.parse_args()

    gs.initPaths(args.local_path)


    #
    # Initialize the logger
    #
    if args.local_path is None:
        CameraNetwork.initialize_logger(
            log_path=gs.DEFAULT_LOG_FOLDER,
            log_level=args.log_level,
            postfix='_camera')

    #
    # In local mode, the camera is working offline.
    #
    if args.local_path is not None or args.offline:
        offline = True
    else:
        offline = False

    try:
        #
        # Setup.
        # Note:
        # The controller is initialized first, for some reasons:
        # - Initialize and get camera info.
        # - Pass a pointer to the controller to the server.
        #
        controller = Controller(offline=offline, local_path=args.local_path)
        server = Server(
            controller=controller, identity=args.identity,
            offline=offline, local_path=args.local_path, local_proxy=args.local_proxy)

        #
        # Start the server and controller
        #
        controller.start()
        server.start()

    except RestartException as e:
        #
        # The user requested a restart of the software.
        #
        logging.exception("User requested to restart program.")
        restart_program()

    except KeyboardInterrupt as e:
        #
        # User stopped the program.
        #
        logging.exception('Program stopped by user.')
    except CameraException as e:
        #
        # Failed starting the camera, might be some USB problem.
        # Note:
        # I delay the reboot so that the tunnel will stay open and
        # enable debugging.
        #
        logging.exception('Failed starting the camera. Rebooting.')
        logging.shutdown()
        time.sleep(120)
        # TODO Long term fix
        os.system('sync; sudo reboot -f')  # Changed from 'sudo reboot', workaround for reboot hanging
    except Exception as e:
        #
        # Failed starting the camera, might be some USB problem.
        # Note:
        # I delay the reboot so that the tunnel will stay open and
        # enable debugging.
        #
        logging.exception('Rebooting. Unknown error:\n{}'.format(repr(e)))
        logging.shutdown()
        time.sleep(120)
        # TODO Long term fix
        os.system('sync; sudo reboot -f')  # Changed from 'sudo reboot', workaround for reboot hanging