Showing posts with label rust. Show all posts
Showing posts with label rust. Show all posts

Saturday, June 17, 2017

implementing a simple language switch using rocket in rust

Let's look how easy it is to implement a simple cookie based language switch in the rocket web framework for the rust programming language. Defining the language type:

In this case there will be support for Dutch and English. PartialEq is derived to be able to compare Lang items with ==.

The Default trait is implemented to define the default language:

The FromStr trait is implemented to allow creating a Lang item from a string.

The Into<&'static str> trait is added to allow the conversion in the other direction.

Finally the FromRequest trait is implemented to allow extracting the "lang" cookie from the request.

It always succeeds and falls back to the default when no cookie or an unknown language is is found. How to use the Lang constraint on a request:

And the language switch page:

And as a cherry on the pie, let's have the language switch page automatically redirect to the referrer. First let's implement a FromRequest trait for our own Referer type:

When it finds a Referer header it uses the content, else the request is forwarded to the next handler. This means that if the request has no Referer header it is not handled, and a 404 will be returned.
Finally let's update the language switch request handler:

Pretty elegant. A recap with all code combined and adding the missing glue:

Friday, December 9, 2016

Persistence for Philips Hue

Two of the lights in our living are Philips Hue lights.
I especially like them for their ability to reach 2000K color temperature (very warm white light), which gives a nice mellow yellowish white light.

We control the lights via normal light switches contained in the light fixture.
Due to the way Philips Hue lights work this implies that whenever we turn on the lights again they go back to the default setting of around 2700K (normal warm white).

In order to fix this once and for all I wrote a little program in rust that does this:

  • poll the state of the lights every 10 seconds (there is no subscribe/notify :( )
  • keep the light state in memory
  • if a light changes from unreachable (usually due to being turned off by the switch) to reachable (turned on by the switch), restore the hue to the last state before it became unreachable
Code is in rust (of course) and can be found at https://github.com/andete/hue_persistence.

Just run it on a local server (I use my shuttle xs36v) and it automatically starts working.
Keep in mind that it can take up to a minute for the Hue system to detect that a light is reachable again.

A short video demoing the system in action: