0

I've created an Android app (written in java) to control the functions of a Kinetic Sand Table, which is based with its functionality on OctoPrint with exclusion of the z axis.

To make sure everything would work prior to hooking up the the SandTable, I decided to start off with attaching the 3D printer. That didn't work because the printer I have is already hooked.

So change of plans, now I tried using the Virtual Printer option. and i'm running OctoPI

What is the problem?

my app is not making API calls! I'm figuring, something wrong with how I'm trying to access the endpoints!

i'm recieving a "Timeout or no connection error occurred" at the app's launch.

I tried to hash map the headers

public class MainActivity extends AppCompatActivity {
//String url = "http://octopiaddress/api/job/start?apikey=mynoneglobalapikey";

    private static final String OctoPrint_IP = "octopiaddress";
    private static final String baseUrl = OctoPrint_IP + "/api";
    private static final String jobUrl = baseUrl + "/job";
    private static final String API_KEY = "mynoneglobalapikey";
    private final String TAG = "tag123";
    private Map<String, String> headers;
    Button playButton;
Spinner patternSpinner;
private static final String files = baseUrl + "/files/local" + API_KEY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set the theme to no title bar
        setTheme(android.R.style.Theme_NoTitleBar);
        // set the content view for your activity
        setContentView(R.layout.activity_main);

        playButton = findViewById(R.id.play_button);

patternSpinner = findViewById(R.id.spinner);

headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("X-Api-Key", API_KEY);

        playButton.setOnClickListener(v -> startPrintJob());

        // The URL to retrieve the patterns from the OctoPrint API
        //String filesUrl = "http://octopiaddress/api/files/local?apikey=mynoneglobalapikey";
        // Make the HTTP request to retrieve the patterns from the OctoPrint API
        JsonArrayRequest request = new JsonArrayRequest(
                Request.Method.GET,
                files,
                null,
                response -> {
                    // Log the response received
                    Log.d(TAG, "Response received: " + response.toString());
                    // Parse the JSON response and add the patterns to the spinner
                    List<String> patternNames = new ArrayList<>();
                    for (int i = 0; i < response.length(); i++) {
                        try {
                            JSONObject pattern = response.getJSONObject(i);
                            String name = pattern.getString("pattern");
                            patternNames.add(name);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    // Creating adapter for spinner
                    ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, patternNames);
                    // Drop down layout style - list view with radio button
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    // attaching data adapter to spinner
                    patternSpinner.setAdapter(adapter);
                    Log.d(TAG, "HTTP request successful");

                },
                this::handleVolleyError

        );

        // Add the request to the Volley request queue
        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        queue.add(request);

        // Set a listener for when a pattern is selected in the spinner
        patternSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedPatternName = (String) parent.getItemAtPosition(position);

                // Construct the JSON object to start the pattern
                JSONObject jsonBody = new JSONObject();
                try {
                    jsonBody.put("name", selectedPatternName);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // Log the JSON body being sent in the request
                Log.d(TAG, "Sending JSON body in the request: " + jsonBody);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Not used in this example
            }
        });
}

    private void startPrintJob() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("command", "start");
        } catch (JSONException e) {
            e.printStackTrace();
            return;
        }

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, jobUrl, jsonObject,
                response -> Toast.makeText(MainActivity.this, "Print started", Toast.LENGTH_SHORT).show(), error -> Toast.makeText(MainActivity.this, "Failed to start print", Toast.LENGTH_SHORT).show()) {
            @Override
            public Map<String, String> getHeaders() {
                return headers;
            }
        };

        Volley.newRequestQueue(this).add(request);
    }

    private void handleVolleyError(VolleyError error) {
        String message;
        if (error instanceof TimeoutError || error instanceof NoConnectionError) {
            message = "Timeout or no connection error occurred";
        } else if (error instanceof AuthFailureError) {
            message = "Authentication error occurred";
        } else if (error instanceof ServerError) {
            message = "Server error occurred";
        } else if (error instanceof NetworkError) {
            message = "Network error occurred";
        } else if (error instanceof ParseError) {
            message = "JSON parse error occurred";
        } else {
            message = "Unknown error occurred";
        }
        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
    }
}
Diana
  • 1
  • 1

0 Answers0