Created on: Sep 19 2017 | Last change: Sep 28 2017

https://ultimaker.com/en/community/23283-inside-the-ultimaker-3-day-2-remote-access-part-1

This is day 2 of "Inside the Ultimaker 3", Remote access.

 

-

 

Other days:

Day 1 - GCode

Day 3 - Remote access (part 2)

 

-

 

A new day, a new piece of information. Yesterday we took a quick look at the changes in gcode files. Which is the core of pretty much any 3D print.

Today, we will look at the remote access trough the network. The remote API is designed to allow control of the machine trough the network. It is what Cura uses to control and monitor the machine remotely.

 

-

 

Even if you are not a software engineer, there is added value for you here. So do not stop reading yet!

The technology behind the API

The API is a REST interface using JSON. That could be 3 new words for you right there. Don't worry.

  • API: Application Programming Interface. Simply meaning it's an thing designed so that applications can talk to eachter. Does not mean we cannot use it as an user. But the end goal is for other applications.
  • REST: Representational State Transfer. Just a fansy way of saying that every "request" you do to the printer is "stateless". Also, just a standardized way of doing things. The really cool part here is that is done trough HTTP.
  • JSON: Javascript Object Notation. A standadized way to represent data. This makes it easier for applications to understand each other. Nothing to worry here, it is quite easy to read by humans.
  • HTTP: Hyper Text Transfer Protocol. For those that missed it, I introduced this term in the REST term. If you are now like "I have seen this before, but where?" that is most likely true. Http is the way your browser talks to a webserver.

 

So, in a nutshell. Our remote access on the printer is actually just a website acting in a standarized way so applications (like Cura) can understand it.

Example time!

You most likely don't have your fansy Ultimaker 3 yet. But I do. Now, first things you need to do is connect your printer to a network. As it's not really possible to access something remotely without access. So setup that WiFi or just plug in a cable.

 

-

 

Next you need your IP address. You can find it in the {SYSTEM}->{Network}->{Connection status} menu. It is those 4 numbers with dots in between. For this example, I'll be using 10.180.1.71, as that is my printer.

 

-

 

Now, you don't need any tool. As you already have the tool for basic viewing of data. You are looking at it. It is your browser. You have this fancy location bar at the top of your browser.

And if we enter http://10.180.1.209/api/v1/system/firmware there, we will see the result:

 

"3.4.12.20161017"

 

That is your firmware version. Could not be simpler. Just so you know, the firmware version is build out of [major].[minor].[revision].[date], every version we use, even internally for testing, gets a new number for tracebility.

 

-

 

I picked a simple example for a reason, so we could look into this at a bit more detail first. The address you entered. Or URL as it is called in fancy computer terms is made up out of these parts:

  • http://: This means we are using http. Part of REST remember?
  • 10.180.1.209: The IP address we looked up on the printer.
  • /api/v1: This means we are accessing our API, and the first version of it. If we ever need to make incompattible changes, we will have a v2 here and keep the v1 for a long as we can.
  • /system: We are accessing the "system" part. System contains things that are not really 3d printer specific. Any device could have these properties.
  • /firmware: We are requesting the "firmware" part of system. Which is defined are returning the firmware version.

 

Having that made clear, in the system we have the following parts:

http://10.180.1.209/api/v1/system/platform - Returns the linux version that we are running on, who cares right?

http://10.180.1.209/api/v1/system/hostname - Returns the hostname of the printer. This is not user configurable and will remain the same unless electronics are replaced. So you can use this to uniquely identify the printer.

http://10.180.1.209/api/v1/system/name - This is the user configurable name. You are asked to configure this during the WiFi setup.

http://10.180.1.209/api/v1/system/firmware - As explained, the current firmware version.

http://10.180.1.209/api/v1/system/memory/used - The amount of memory in use by the system.

http://10.180.1.209/api/v1/system/memory/total - The amount of memory available in total.

http://10.180.1.209/api/v1/system/memory/log - The system keeps a log of many state changes, this API accesses that log. More on it later.

http://10.180.1.209/api/v1/system/memory/language - The configured language, we are preparing for providing the printer in your native language as well. But we decided not to delay the release for this. So this is always empty right now.

http://10.180.1.209/api/v1/system/memory/country - 2 letter country code, if configured. This is done during the WiFi setup. WiFi hardware needs to be configured for your region to make sure the proper WiFi channels are used. If you don't use WiFi this is most likely empty.

 

-

 

However, if you want all of these in a single go. You can just request:

http://10.180.1.209/api/v1/system

Which will respond with:

 

{"country": "", "firmware": "3.4.12.20161017", "hostname": "ultimakersystem-ccbdd3000229", "language": "en", "log": ["...", "..."], "memory": {"total": 1057030144, "used": 125394944}, "name": "Ultimaker-000229", "platform": "Linux-4.2.0-rc7-opinicus-00001-g63c264e-armv7l-with-debian-8.1"}

 

Note that I cut out the log data, the rest is a JSON response. It looks a bit hard to read, but computers have no problem in reading it. There are however, tools to format it in a more readable way:

 

{
    "country": "",
    "firmware": "3.4.12.20161017",
    "hostname": "ultimakersystem-ccbdd3000229",
    "language": "en",
    "log": [
        "...",
        "..."
    ],
    "memory": {
        "total": 1057030144,
        "used": 125394944
    },
    "name": "Ultimaker-000229",
    "platform": "Linux-4.2.0-rc7-opinicus-00001-g63c264e-armv7l-with-debian-8.1"
}

 

There is http://10.180.1.209/log.html currently on the printer that uses /api/v1/system/log to view the latest log data in a more readable format. It was quickly put together and I'm sure we will expand to a better web interface for the printer in the future.

But, it is a 3D printer!

Yes yes. It is a 3D printer. So we want 3D printer data. And we have that. There are 2 basic important start points:

http://10.180.1.209/api/v1/printer

http://10.180.1.209/api/v1/print_job

The first contains a lot of information about the printer itself. And all of those things can be accessed in the same way as the system part.

The second contains information about the currently running print job. If no job is running, you will get a "not found" error. For the technical people, this includes status code 404.

/api/v1/printer

Let us look at the /api/v1/printer first. This as the following sub parts:

/api/v1/printer/led - Part to access the printer casing leds.

/api/v1/printer/heads - Part to access the printer head (more on this one later)

/api/v1/printer/bed - Part to access information of the printer bed, limited to current and target temperature.

/api/v1/printer/status - Best thing to look at first. Basic status of the printer. This could be "idle", "printing", "error", "maintenance" or "booting". Will explain in a bit.

/api/v1/printer/beep - Nothing to read from here. Can be written to to make the printer beep.

/api/v1/printer/diagnostics - Different diagnostic functions. Retreiving this part does not do anything, but it has sub parts that are not collected in the /api/v1/printer that can be used for in depth diagnostic functions. We WILL go over this for sure.

/api/v1/printer/network - Contains the WiFi and Ethernet information. Mostly usefull to see if it is cable of WiFi connected. But the WiFi setup process uses this to connect to a network and to see which networks are available.

/api/v1/printer/status

The main status of the printer, can be:

  • idle: Printer is doing nothing and ready for action.
  • printing: Printer is actively printing something, or still needs to be emptied, print_job needs to be retreived for details.
  • error: Something is wrong with the printer, and requires action at the printer itself to be corrected.
  • maintenance: Someone is actively doing things with the printer, for example changing materials or PrintCores.
  • booting: Printer is still starting up. This only lasts for a few seconds.

 

/api/v1/printer/heads

The printer has a single head. However, the API is prepared for possible futures, so it accounts for multiple heads already. Do not take this as a reason to think we are developing multi head printers. It just good engineering practice to have this in place when it costs almost no effort.

 

-

 

So, the actual part that we need to access for print head information is:

http://10.180.1.209/api/v1/printer/heads/0

Software engineers are mighty annoying, as we start counting at 0. So the first head is identified by 0. The first hotend is identified by 0 and the second one with 1.

 

-

 

In here we have some basic settings like acceleration values, maximum speeds, the current position and linked extruders with their hotends. Feel free to explore.

As you are all in love with the current hotend temperature, I will show you that one:

http://10.180.1.209/...0/hotend/temperature

http://10.180.1.209/...1/hotend/temperature

For the first and second extruder. But, by sheer magic, we also know what type of PrintCore you have in the machine, which can be seen from:

http://10.180.1.209/...xtruders/0/hotend/id

In my case, it returns "AA 0.4"

There is the fan entry:

http://10.180.1.209/api/v1/printer/heads/0/fan

Which contains the print cooling fan speed in 0% to 100% (not 0 to 255 as you see in GCode). The head cooling fan state is not accessible, but directly linked to the hotend temperatures.

Small note of warning

There is http://10.180.1.209/...active_material/GUID. However, this breaks with the rest of the API and will be removed. Use the lower case http://10.180.1.209/...active_material/guidinstead.

/api/v1/printer/diagnostics

Currently, the only intressing part here is:

http://10.180.1.209/.../temperature_flow/10

The last number can be changed up to 20000, but that might take a while to load. The printer takes about 10 samples per second.

The result of this is:

 

[
["Time", "temperature0", "target0", "heater0", "flow_sensor0", "flow_steps0", "temperature1", "target1", "heater1", "flow_sensor1", "flow_steps1", "bed_temperature", "bed_target", "bed_heater"],
[62868.34765625, 23.100000381469727, 0.0, 0.0, 0.0, 0.0, 23.0, 0.0, 0.0, 0.0, 0.0, 18.299999237060547, 0.0, 0.0],
[62868.453125, 23.100000381469727, 0.0, 0.0, 0.0, 0.0, 23.0, 0.0, 0.0, 0.0, 0.0, 18.700000762939453, 0.0, 0.0],
[62868.5625, 23.100000381469727, 0.0, 0.0, 0.0, 0.0, 23.0, 0.0, 0.0, 0.0, 0.0, 18.399999618530273, 0.0, 0.0],
[62868.671875, 23.100000381469727, 0.0, 0.0, 0.0, 0.0, 23.0, 0.0, 0.0, 0.0, 0.0, 18.399999618530273, 0.0, 0.0],
[62868.78125, 23.100000381469727, 0.0, 0.0, 0.0, 0.0, 23.0, 0.0, 0.0, 0.0, 0.0, 18.399999618530273, 0.0, 0.0],
[62868.890625, 23.100000381469727, 0.0, 0.0, 0.0, 0.0, 23.0, 0.0, 0.0, 0.0, 0.0, 18.5, 0.0, 0.0],
[62869.00390625, 23.100000381469727, 0.0, 0.0, 0.0, 0.0, 23.0, 0.0, 0.0, 0.0, 0.0, 18.299999237060547, 0.0, 0.0],
[62869.11328125, 23.100000381469727, 0.0, 0.0, 0.0, 0.0, 23.0, 0.0, 0.0, 0.0, 0.0, 18.700000762939453, 0.0, 0.0],
[62869.22265625, 23.100000381469727, 0.0, 0.0, 0.0, 0.0, 23.0, 0.0, 0.0, 0.0, 0.0, 18.5, 0.0, 0.0],
[62869.328125, 23.100000381469727, 0.0, 0.0, 0.0, 0.0, 23.0, 0.0, 0.0, 0.0, 0.0, 18.0, 0.0, 0.0]
]

 

It is a history of temperature data for both hotends, and the bed. There is the current temperature, the target temperature and the amount of heating output. There is also something in there called "flow", but that returns 0 for you. Sorry.

Now, this data is a bit hard to parse. But lucky for you, if you want to save this data you can do so very easy, by adding ?csv=1 behind it. Note that this is the only API part that supports this download.

http://10.180.1.209/...rature_flow/10?csv=1

However, like this you can store it for later viewing, or do all kinds of crazy math and graphing with it, as microsoft-excel or libreoffice-calc can both import this file with relative ease.

 

-

 

There is http://10.180.1.209/temperature.html currently on the printer that uses this data to plot a real-time temperature graph. It is not an official feature of the printer and something we used during development. But it is damn cool.

I'm a 100% sure will will expand this diagnostics part later with more data collection. So stay tuned for firmware updates.

/api/v1/print_job

http://10.180.1.209/api/v1/print_job

That's the part that returns the currently active print job. Or it returns:

 

{"message": "Not found"}

 

If there is no print job running. It does not return a whole lot of information, but I think it is the most important information that you can have about the printer. So I will go over it in great detail.

A result when a job is running looks like:

 

{
    "name": "Most awesome PVA print ever done.gcode",
    "progress": 0,
    "state": "pre_print",
    "time_elapsed": 0,
    "time_total": 0
}

 

Initially, the most important entry to look at is the "state", this is different from the printer status. And can have the following values:

  • printing: Print is currently busy. Most common state.
  • pausing: Print was busy and the printer is in the process of going to the paused state. This usually does not last long.
  • paused: Print is paused and thus will not finish without used interaction.
  • resuming: Print is resuming after a pause. Could be heating up the hotend again so this can take a while.
  • pre_print: Preparing to print. This is the state before any gcode is run. Active leveling is done during this state as well as heating up the bed/hotends.
  • post_print: Print is finished, cooling down things and homing the head. This state lasts a while because of how the hotends are properly released from filament. (user can skip part of this at the machine)
  • wait_cleanup: Print is fully finished, everything is cooled down. But the print still needs to be removed from the printer. This waits for a conformation of the user at the printer itself.

 

The progress value is from 0.0 to 1.0 for 0% to 100%, the time values are in seconds. Note that the time_total will be updated during a print as the estimate on when the print is finished will be adjusted during printing. Printing estimates from Cura are usually within the 5% error range. And due to some extra time markers we added the estimate is generally less then 1% off after 2 layers of printing.

 

-

 

If you only care about a single value, you can request just that, just like all the other parts of the API.

http://10.180.1.209/api/v1/print_job/name

http://10.180.1.209/api/v1/print_job/state

http://10.180.1.209/api/v1/print_job/progress

http://10.180.1.209/api/v1/print_job/time_elapsed

http://10.180.1.209/api/v1/print_job/time_total

Documentation

I've uploaded our work-in-progress documentation files at: http://software.ultimaker.com/jedi/api/2016.10.20/, these can be viewed with http://editor.swagger.io/. Note that there could be errors and mistakes in this documentation.

Wrapping it up

This is day 2. I think this is a information overload for quite some people already. I also have actual work to do. Tomorrow I will go into the details of using the API to actually change things. That will be a lot more technical then today. Expect code.

Also, I don't know how many days I will fill on remote access. As there is a lot to cover. Stay tuned.

 

-

 

 

-

 

Disclaimer: Any information presented here could be wrong. I did my best to proof read everything, but it could conflict with official statements and the actual behavior of the printer.

 

https://ultimaker.com/en/community/23329-inside-the-ultimaker-3-day-3-remote-access-part-2

 

This is day 3 of "Inside the Ultimaker 3", Remote access part 2

 

-

 

Other days:

Day 1 - GCode

Day 2 - Remote access part 1

 

-

 

Welcome back. Yesterday we look at accessing data from the printer. Today we will look at changing data in the printer from remote access.

 

-

 

This is a whole lot more technical and complex then just accessing data. The reason for this is security and mistakes. First off, you might not want everyone on your network to start/abort/pause prints. And you might, by mistake, control a different printer then you wanted.

Think excidental use is uncommon? It happened at our office during development. And think how often you send something to a 2D printer to find it at a different printer then you expected.

Security!

First off, we had quite a few discussions about this at the office. As you need to have the proper trade-off between security and ease-of-use. Also, security is not an easy subject. Things that might look secure don't have to be. Things that are secure might be a pain to use.

 

-

 

So, we made the following decisions:

  • Reading of data is always possible. To make monitoring of printers easy, and while you can access camera feeds and print head positions. It's not possible to get the exact gcode file out of the printer. Thus the model is still quite secure.
  • Any "change" in the printer requires authentication. A change can be starting a print, aborting a print, or even changing the LED colors.
  • Authentication is done by a pairing mechanism. So your printer and Cura, a phone app, or any application you want need to "pair up". Most of this is invisible to the user.
  • Physical access is access. So if you can touch the printer you should also be able to pair up.
  • Multiple applications/devices can be paired with the printer at the same time.

 

The end result of this means that if you have an Ultimaker 3. And you connect with Cura for the first time, you need to say on the printer "I allow this Cura to use this printer".

20161021_110136

 

-

 

On the technical side, this means any REST request to the printer that is not a HTTP GET request requires this pairing to be done correctly.

Pairing, under the hood.

The pairing process is actually a multi step process. These steps are:

 

  1. The application request a new ID/KEY combination from the printer. It does this with the name of the application and the name of the user that wants to access the printer.
  2. The printer returns this new ID/KEY combination to the application.
  3. The printer shows the dialog with DENY/ALLOW
  4. Until the user has selected ALLOW on the printer, this ID/KEY combination is not valid. The application keeps checking if the user selected allow or deny on the printer.
  5. Once ALLOW is selected, the ID/KEY combination can be used as username/password combination for HTTP Digest.

 

HTTP Digest...

The nice things about standards is, that you have so many to choose from. For security we looked for something that was quite easy to implement, but offered the security we needed.

While we did look at HTTPS, the problem there is that you need certificates, and which the openness of the devices this became complex really quick.

 

-

 

So, we looked at RFC 2617, known as HTTP Digest authentication. This standard on top of HTTP allows for easy username/password checking, while being protected against:

  • Man-in-the-middle attacks
  • Eavedrop attacks
  • Replay attacks

 

However, there is one problem with the standard. It says that you can always fall back to lesser secure modes. Which offer limited or no security at all.

So, we chose to implement one of the strongest forms of HTTP Digest, and REQUIRE it, instead of making all the security features optional.

 

-

 

This all sounds very complex. However, if you are a software engineer and you want to talk to the printer. You most likely have a library that will solve this for you.

However, as suggested in the other topic, postman is implements Digest auth as such a low level that it is impossible to get this to work consistantly.

The HTTP librart of QT has no problem with this. The "requests" library from python can also be used with almost no effort. I will provide an example in a bit.

The cop-out

If you are developing, and the security is in your way and you want to deal with it later. There is a cop-out. All this complex digest and pairing is disabled in the WiFi setup right now. As you are a local hotspot. This also made it easier to develop the WiFi setup.

So, for quick testing, you can start a WiFi setup, and connect to the local hotspot, and talk to the printer without any security.

The real thing

Finally, some actual things. There are 3 API parts that are important at first.

They are:

  • /api/v1/auth/verify: Used to check if your authentication id/key is still valid. This is the only API which requires authentication on a GET request. If you go here with your browser, you will get the username/password popup.
  • /api/v1/auth/request: This is used to setup a new pairing request. This needs to be done as a POST request, with 2 parameters "application" and "user". The API will return a JSON result with an "id" and a "key". This is your username and password for the HTTP Digest. However, this isn't valid till you pressed "ALLOW" at the printer. If you press "DENY", this combination of ID/KEY is discarded.
  • /api/v1/auth/check/{id}: This can be used to check the status of your new request. {id} should be filled with the result from the /api/v1/auth/request call. The result will be one of: "unauthorized", "authorized" or "unknown". "unauthorized" means that the user pressed "DENY" and you can discard the ID/KEY. "authorized" means "ALLOW" is pressed and you can now start using this ID/KEY. "unknown" means that the user hasn't done anything yet and you should try again.

 

Side effect: Currently, the printer only allows for 1 pairing request at the same time. If you send a 2nd request, the first one is denied automaticly.

 

-

 

So, in pseudo code:

 

if no (id, key) or "api/v1/auth/verify" == "unauthorized" then
    id, key = post("api/v1/auth/request", application="Test", user="Daid")
    while "api/v1/auth/check/" + id == "unknown" do
        sleep 1 second
    end
    if "api/v1/auth/check/" + id == "unauthorized" then
        abort: failed to pair up.
    end
end
//We now have a valid id/key combination.

 

All that, just to pair up.

Doing actual things

Still following me? Good. If not, sorry, this is all very technical. I will provide example code at the end.

Now, we want to do thing. And there are quite a few things we can do with the API. I will cover a few things.

  • Changing the printer name. Why? It's the easiest API.
  • Changing the LED colors and heating up things.
  • Starting a print job. Why? It's the most important API.
  • Aborting a print job. After you started it, you might decide that you do not want it. (Or the print could be failing. But that is rare right?)

 

Change the name

Remember from day 1, the printer name was read at /api/v1/system/name. Now, we can set the printer name the same way, but instead of a HTTP GET, we need to use a HTTP PUT.

Now, all our APIs require JSON as input. This means a few things, the data in the PUT request needs to be valid JSON. And the Content-type header of the request needs to be set to "application/json".

If we want to set our printer name to MyUltimaker3, we get a request that looks like this:

 

PUT /api/v1/system/name HTTP/1.1
Host: 10.180.1.209
Connection: keep-alive
Accept: */*
User-Agent: python-requests/2.11.1
Accept-Encoding: gzip, deflate
Content-type: application/json
Content-Length: 14
Authorization: Digest username="2af8417b8501e0422e191d5fbe64209e", realm="Jedi-API", nonce="76684432bdb9a1a386a877e41468a681", uri="/api/v1/system/name", response="50da68df53c0eeb9906212560b0077aa", qop="auth", nc=00000003, cnonce="b2316951bb03e010"

"MyUltimaker3"

 

This is an actual request that I logged. My auth ID is "2af8417b8501e0422e191d5fbe64209e" which you can see in the Authorization part, my auth KEY is "f9a43169c49bb9e81d670c946d6358dac428b820e0d9676e15b63bdcf57be45f", which you cannot see, and is used to generate the "response".

Placing this here to possibly assist in debugging if you are doing your own implementation of HTTP Digest.

The printer name is under some restrictions. So your printer might not always accept the new name.

Changing the LEDs and heating up.

Important note, in firmware versions 3.4.x these APIs are broken. They should be fixed as of firmware version 3.5.x

Changing the temperature. This is easy, we want to set the target temperature. The APIs for this are:

  • /api/v1/printer/heads/0/extruders/0/hotend/temperature/target
  • /api/v1/printer/heads/0/extruders/1/hotend/temperature/target
  • /api/v1/printer/bed/temperature/target

 

And, just like the name, you can just put a value into it to change the target. As this needs to be in JSON format, it needs to be a number without quotes, while the name was a string and thus needed quotes.

Setting the LED brightness and colors can be done in a single call. There are the APIs:

  • /api/v1/printer/led
  • /api/v1/printer/led/brightness
  • /api/v1/printer/led/saturation
  • /api/v1/printer/led/hue

 

The last 3 set each value seperately, but the first one can be used to set all 3 in one go. You do this by sending a single json dictionary containing the proper key/value combinations to /api/v1/printer/led. Once again, this needs to be a HTTP PUT request.

Example:

 

{"brightness": 50.0, "saturation": 20.0, "hue": 100.0}

 

Note, the current implementation of the API returns no status when you do this. So you do not know exactly if the request was accepted.

Starting a print

Starting a print is the most complex call there is, as you need to send a multi-part file upload. If you are not using a library for HTTP communication. Forget about it.

Else, it's easy, just do a HTTP POST request with a file upload to /api/v1/print_job, with the name of the file parameter to "file".

Abort/pausing a print job

You might want to abort or pause a print job remotely. This is all done trough the /api/v1/print_job/state API. Once again with PUT requests.

You need to PUT the new state you want into this state API, in the form {"target": "new state"}. There are 3 possible things you can PUT here.

  • abort, requests the print to be aborted.
  • pause, if the print isn't paused it will do so now.
  • print, if the print is paused, it will resume printing.

 

Note that this API in the current implementation always reports no content. So you need to poll the state to see if you request was actually honored.

Wrapping it up.

I'll just finish with my python3 code that can talk to the Ultimaker 3. You can use this as an example, or if you make an open-source product you can use it directly.

 

#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import requests
import json
import os
import time

## Ultimaker 3 API access class.
#  Allows for access of the Ultimaker 3 API with authentication.
#  Uses the python requests library to do the actual http requests, which does most of the work for us.
class Ultimaker3:
    # @param ip: IP address of the printer
    # @param application: name of the application in string form, used during authentication requests and is shown on the printer.
    def __init__(self, ip, application):
        self.__ip = ip
        self.__application = application
        self.__session = requests.sessions.Session()
        self.__setAuthData("", "")
    
    # Set new authentication data, authentication data is send with each HTTP request to make sure we can PUT/POST data.
    def __setAuthData(self, id, key):
        self.__auth_id = id
        self.__auth_key = key
        self.__auth = requests.auth.HTTPDigestAuth(self.__auth_id, self.__auth_key)
    
    # Load authentication data from a file. If this file does not exists, or the data in it is invalid, we request a new authentication set and store it in the file.
    def loadAuth(self, filename):
        try:
            data = json.load(open(filename, "rt"))
            self.__setAuthData(data["id"], data["key"])
        except IOError:
            self.__checkAuth()
            self.saveAuth(filename)
        if not self.__checkAuth():
            self.saveAuth(filename)

    # Save the authentication data to a file.
    def saveAuth(self, filename):
        json.dump({"id": self.__auth_id, "key": self.__auth_key}, open(filename, "wt"))
    
    # Check if our authentication is valid, and if it is not request a new ID/KEY combination, this function can block till the user selected ALLOW/DENY on the printer.
    def __checkAuth(self):
        if self.__auth_id == "" or self.get("api/v1/auth/verify").status_code != 200:
            print("Auth check failed, requesting new authentication")
            response = self.post("api/v1/auth/request", data={"application": self.__application, "user": os.getlogin()})
            if response.status_code != 200:
                raise RuntimeError("Failed to request new API key")
            data = response.json()
            self.__setAuthData(data["id"], data["key"])
            while True:
                time.sleep(1)
                response = self.get("api/v1/auth/check/%s" % (self.__auth_id))
                data = response.json()
                print(data["message"])
                if data["message"] == "authorized":
                    print("Authorized.")
                    break
                if data["message"] == "unauthorized":
                    raise RuntimeError("Authorization denied")
            return False
        return True
    
    # Do a new HTTP request to the printer. It formats data as JSON, and fills in the IP part of the URL.
    def request(self, method, path, **kwargs):
        if "data" in kwargs:
            kwargs["data"] = json.dumps(kwargs["data"])
            if "headers" not in kwargs:
                kwargs["headers"] = {"Content-type": "application/json"}
        return self.__session.request(method, "http://%s/%s" % (self.__ip, path), auth=self.__auth, **kwargs)

    # Shorthand function to do a "GET" request.
    def get(self, path, **kwargs):
        return self.request("get", path, **kwargs)

    # Shorthand function to do a "PUT" request.
    def put(self, path, **kwargs):
        return self.request("put", path, **kwargs)

    # Shorthand function to do a "POST" request.
    def post(self, path, **kwargs):
        return self.request("post", path, **kwargs)

 

It's a very basic wrapper around the very new "requests" library for python. But it helps in setting up the authentication.

Example usage:

 

api = Ultimaker3("10.180.1.209", "Test script")
api.loadAuth("auth.data")

# Get all the system data
system = api.get("api/v1/system").json()
print(system["name"])
# Change the system name
result = api.put("api/v1/system/name", data="MyUltimaker3")
print(result.json())

# Set the target hotend temperature to 100C, and then back to 0.
print(api.get("api/v1/printer/heads/0/extruders/0/hotend/temperature").json())
result = api.put("api/v1/printer/heads/0/extruders/0/hotend/temperature/target", data=100.0).json()
print(api.get("api/v1/printer/heads/0/extruders/0/hotend/temperature").json())
result = api.put("api/v1/printer/heads/0/extruders/0/hotend/temperature/target", data=0.0).json()
print(api.get("api/v1/printer/heads/0/extruders/0/hotend/temperature").json())

# Change the LEDs
api.put("api/v1/printer/led", data={"brightness": 50.0, "saturation": 20.0, "hue": 100.0})

# Start a print job.
result = api.post("api/v1/print_job", files={"file": ("UM3_Box_20x20x10.gcode", open("UM3_Box_20x20x10.gcode", "rb"))})
print(result.content)

# Pause the print
api.put("api/v1/print_job/state", data={"target": "pause"})
# Resume the print
api.put("api/v1/print_job/state", data={"target": "print"})
# Abort the print
api.put("api/v1/print_job/state", data={"target": "abort"})

 

 

-

 

 

-

 

Disclaimer: Any information presented here could be wrong. I did my best to proof read everything, but it could confict with official statements and the actual behavior of the printer. This post is purely informative and does not necessary reflect the official view of Ultimaker.