Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue #29: Module that retrieves microscope config from Tagarno Open API #44

Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env.template
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ NACHET_SUBSCRIPTION_ID=
NACHET_RESOURCE_GROUP=
NACHET_WORKSPACE=
NACHET_MODEL=
MICROSCOPE_URL=
3 changes: 3 additions & 0 deletions custom_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,6 @@ class ValidateEnvVariablesError(Exception):

class ServerError(Exception):
pass

class OpenApiError(Exception):
k-allagbe marked this conversation as resolved.
Show resolved Hide resolved
pass
66 changes: 66 additions & 0 deletions microscope_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import json
k-allagbe marked this conversation as resolved.
Show resolved Hide resolved
import requests
k-allagbe marked this conversation as resolved.
Show resolved Hide resolved
from custom_exceptions import OpenApiError
from dotenv import load_dotenv
import os

load_dotenv()

methods = [
k-allagbe marked this conversation as resolved.
Show resolved Hide resolved
"getVersion", # Returns microscope version
"getFieldOfView", # Returns FoV as an int value (μm)
"getZoomDirect", # Returns current zoom as string hex value
"getFocusDirect", # Returns current focus as string hex value
"getContrast", # Returns position of the Contrast slider
"getSaturation", # Returns position of the Saturation slider
"getSharpness" # Returns position of the Sharpness slider
]

MICROSCOPE_URL = os.getenv("MICROSCOPE_URL")
params = {"id": 6969}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest passing the id to the get_microscope_configuration function as an argument. Then you could do:

if __name__ == "__main__":
    try:
        microscope_id = 6969
        config = get_microscope_configuration(microscope_id)
        if config:
            print(config)
    except OpenApiError as e:
        print(f"Error: {e}")

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not the microscope's ID, it's just an int that indentifies the request. As discussed, I'm generating a UUID instead of a hard-coded value.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it. In that case, I would create the id on the fly inside the post_request function.
Example:

def post_request(microscope_url, method, headers=HEADERS):
    id = int(uuid.uuid4())
    url = f"{microscope_url}?jsonrpc=2.0&method={method}&id={id}"

    data = json.dumps({
        "jsonrpc": "2.0",
        "method": method,
        "id": id,
    })
...

And if the id's purpose is for verification, then maybe check that the response's id matches.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, function parameters are usually lowercase. Same for def get_microscope_configuration(METHODS):. Not a problem per se, but could be confusing.

headers = {'Content-Type': 'application/json'}
k-allagbe marked this conversation as resolved.
Show resolved Hide resolved

def post_request(MICROSCOPE_URL, method, params, headers):
url = f"{MICROSCOPE_URL}?jsonrpc=2.0&method={method}&id={params['id']}"

data = json.dumps({
"jsonrpc": "2.0",
"method": method,
"id": params['id'],
})

try:
resp = requests.post(url, data=data, headers=headers)
return resp.json()
except OpenApiError as e:
k-allagbe marked this conversation as resolved.
Show resolved Hide resolved
print(f"Request Error: {e}")

def is_hex(s):
try:
int(s, 16)
return True
except ValueError:
return False

def get_microscope_configuration():
config = {}
for method in methods:
k-allagbe marked this conversation as resolved.
Show resolved Hide resolved
resp = post_request(MICROSCOPE_URL, method, params, headers)
result = resp["result"]

# Check if the response is in hexadecimal and convert it
if isinstance(result, str) and is_hex(result):
result = int(result, 16)

config[method] = result

return json.dumps(config, indent=4)
k-allagbe marked this conversation as resolved.
Show resolved Hide resolved


if __name__ == "__main__":
try:
config = get_microscope_configuration()
if config:
print(config)
except OpenApiError as e:
print(f"Error: {e}")
Loading