Metadata-Version: 2.5
Name: p2api
Version: 1.2.9
Summary: Binding for the ESO phase 2 programmatic API
Project-URL: Homepage, https://www.eso.org/copdemo/apidoc/index.html
Author-email: Thomas Bierwirth <thomas.bierwirth@eso.org>, John Pritchard <john.pritchard@eso.org>
License: MIT License
        
        Copyright (c) 2018-present Thomas Bierwirth and other contributors
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: API,ESO,Observation,Phase2,Preparation,Programmatic
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Dist: keyring
Requires-Dist: requests
Description-Content-Type: text/markdown

# p2api

The [ESO](https://www.eso.org/public/) [Phase 2](https://www.eso.org/sci/observing/phase2.html) Application Programming Interface (API) uses the lightweight [JSON](<https://en.wikipedia.org/wiki/JSON>) standard as data format to exchange information between your application and the Phase 2 server at ESO. In order to program more conveniently against the API, it is helpful to create small, [language-specific bindings](<https://en.wikipedia.org/wiki/Language_binding>) to the API. We provide a simple example binding for Python, i.e. p2api.

As of version 1.2.3: Support for triggering RRMs and getting their status as well as that of the system.

As of version 1.2.3: Support for triggering RRMs is posibly actually functional!

As of version 1.1.0: Added support for triggering RRMs and ToOs.

As of version 1.0.10: Removed script p2api_add_absolute_time_intervals.

As of version 1.0.7: Improved backward compatibility for older systems.

As of version 1.0.6: Added script p2api_add_absolute_time_intervals.

As of version 1.0.3: support for \<url\>,\<access_token\> constructor.

As of version 0.97.2: support for La Silla.

Please see the [ESO-USD p2api](<http://eso.org/sci/observing/phase2/p2intro/Phase2API.html>) page for more details.

Phase 2 programmatic API documentation can be found [here](<https://www.eso.org/copdemo/apidoc/>).

## Create a dedicated Virtual Environment for p2api

```bash
bash
python -m venv "${HOME}/envs/p2api"
. "${HOME}/envs/p2api/bin/activate"
python -m pip install --upgrade pip
python -m pip install p2api
```

### RRM observations

#### Major change to authentication for RRM Triggers

Prior to this REST-API, trigger authentication was via the pre-authorized **trigger-code**, i.e. the unique combination of "account-code", instrument name and OB name.

With the REST-API, trigger authentication is based on **p2-credentials authentication**. This means that a given OB can be triggered if the authenticated P2 user has permission to "see"/edit the OB (i.e. the PI of the run and **all phase-2-delegates**). In addition the run must be of RRM-type, and the OB must be in status '+' (for testing 'D'="Certified" is also allowed.)

#### Prepare the environment

First activate the environment ( if it is not already activated):

```bash
bash
. "${HOME}/envs/p2api/bin/activate"
```

Next save your ESO User Portal credentials in the keyring if you want to be able to trigger without being prompted for the password each time:

```bash
up_username=<ESO_User_Portal_username>
p2api_rrm_trigger -u ${up_username} -S
```

#### Testing

Check the status of the RRM system:

```bash
up_username=<ESO_User_Portal_username>
p2api_rrm_system_status -u ${up_username} \
    --env=production \
    --obId=1234567
```

If the system is ONLINE, then you are ready to make a test trigger:

```bash
up_username=<ESO_User_Portal_username>
p2api_rrm_trigger -u ${up_username} \
    --env=production \
    --obId=1234567 \
    --RA=10:20:30.000 --DEC=-35:01:30.600 \
    --finding_charts /<absolute>/<file>/<path>/<fc_filename_1.jpg>,<relative>/<file>/<path>/<fc_filename_2.jpg>
```

This command will submit the trigger and then monitor execution progress, creation of ticket and upload of Finding Charts. In testing mode it will create (if needed) a ticket for your **run** that will be used for all trigger tests (rather an a **new** ticket for each trigger-test.)

#### Real triggers

To check the system status of the LIVE RRM system and/or to make an actual trigger, not just a **test** trigger & ticket, add the command line argument ```--NOT_A_TEST``` to each of the above commands. For real (non-test) triggers a new ticket will be create for each trigger.

Check the status of the RRM system:

```bash
up_username=<ESO_User_Portal_username>
p2api_rrm_system_status -u ${up_username} \
    --env=production \
    --obId=1234567 \
    --NOT_A_TEST
```

If the system is ONLINE, then you are ready to make a test trigger:

```bash
up_username=<ESO_User_Portal_username>
p2api_rrm_trigger -u ${up_username} \
    --env=production \
    --obId=1234567 \
    --RA=10:20:30.000 --DEC=-35:01:30.600 \
    --finding_charts /<absolute>/<file>/<path>/<fc_filename_1.jpg>,<relative>/<file>/<path>/<fc_filename_2.jpg> \
    --NOT_A_TEST
```

This command will submit the trigger and then monitor execution progress, creation of ticket and upload of Finding Charts. In testing mode it will create (if needed) a ticket for your **run** that will be used for all trigger tests (rather an a **new** ticket for each trigger-test.)

### Integration into your own python tool(s)

**The following is currently un-tested, their maybe bugs, please contact ESO-USD via ticket if you need help...**

To integrate the utilities into your own python tool(s) the following gives one way to do that. Feel free to inspect the p2api code to figure out the best way to do it yourself.

In all of the following RRM methods, the object ```options``` is assumed to exist (e.g. as returned by a get_options class based on Python built-in class ```argparse.ArgumentParser```, not all attributes have to be specified as command line options, they can be addded to the options object by the code). It must have the following attributes:

```
env:str       # ehe name of the environment, by default 'production'
user:str      # the user portal username
pw:str        # the password of the user portal user
obId:int      # the OB Id number
testing:bool  # True|False for testing
quiet:bool    # True|False for quiet logging|actions
debug:bool    # True|False for debug logging|actions
```

The additional attributes are **required** for the rrm_trigger_oneOB method:

```
RA:str             # hh:mm:ss.sss
DEC:str            # ±dd:mm:ss.sss
phone:str          # Contact phone number for triggerer (or delegate)
notify:str         # comma separated list of email addresses to include in trigger ticket CCs
calibrations:bool  # True|False for Additional calibrations required. Please specify details in comments.
comments:str       # Comments for trigger
```

The additional attributes are **optional** for the rrm_trigger_oneOB method:

```
finding_charts:str # comma separated list of finding chart filenames (relative or absolute paths)
```

Get the system status and then trigger an RRM OB execution is fthe system is ONLINE.

```python
    overall_sdt=datetime.datetime.now(tz=datetime.timezone.utc)

    import logging
    import datetime
    import p2api
    from p2api.utils.rrm_system_status import oneOB as rrm_system_status_oneOB
    from p2api.utils.rrm_trigger import oneOB as rrm_trigger_oneOB
    logger=logging.getLogger()
    api=p2api.ApiConnection(environment=options.env, username=options.user, password=options.pw)

    # system status
    r=rrm_system_status_oneOB(
       api=api,
       options=options,
       obId=options.obId,
       overall_sdt=overall_sdt,
    )
    if r is not None :
        if r.status_code in [200,201,202,204] :
            rj=r.json()
            rrm_syestem_status=rj['system_state']['system_state']
        else :
            logger.error("Query returned unexpected response status_code")
    else :
        logger.error("Query returned unexpected response")

    if rrm_system_status == 4 :
        # Make trigger
        trigger_ticket_status=rrm_trigger_oneOB(
            api=api,
            options=options,
            obId=options.obId,
            overall_sdt=overall_sdt,
        )
```
