Rust Library for controlling divoom devices that support REST APIs, such as pixoo-64.

Overview

Divoom

Divoom

Rust Library for controlling divoom devices that support REST APIs, such as pixoo-64 (and from how divoom's api/doc organizes, maybe more in the future).

Crates.io Documentation License: Apache 2.0

// Get current channel
use divoom::*;

println!(
    "{:?}",
    PixooClient::new("192.168.0.123").get_current_channel().await?
);

// Output: Clock

How to use

The library contains 2 major parts:

  • Divoom service APIs, that is used for talking to Divoom's backend service for device discovery etc.
  • Pixoo device APIs, that is used for talking to a specific device via its REST APIs.

Divoom service APIs

To discover all devices in your LAN, we can use the get_same_lan_devices API to get all devices from Divoom's backend service.

use divoom::*;

let divoom = DivoomServiceClient::new();
let devices = divoom.get_same_lan_devices().await?;
devices.iter().for_each(|x| println!("{:?}", x));

This will output:

DivoomDeviceInfo { device_name: "Pixoo", device_id: 300000001, device_private_ip: "192.168.0.123" }

Pixoo device APIs

Once we get the device ip, we can use it to create a pixoo client and start talking to it:

use divoom::*;

let pixoo = PixooClient::new("192.168.0.123");
let result = pixoo.get_current_channel().await?;
println!("{:?}", result);

This will output:

Clock

Currently, we have these APIs supported:

  • Channel APIs
    • Select channel
    • Get current channel
    • Select clock
    • Get selected clock info
    • Select cloud channel
    • Select visualizer
    • Select custom page
  • System/Device APIs
    • Get device settings
    • Get device time
    • Set device brightness
    • Set device time
    • Set device high light mode
    • Set device hour mode
    • Set device mirror mode
    • Set device rotation angle
    • Set device screen power state
    • Set device temperature unit
    • Set device time zone
    • Set device weather area
    • Set device white balance
  • Tools APIs
    • Set countdown tool
    • Set noise tool
    • Set scoreboard tool
    • Set stopwatch tool
  • Animation APIs
    • Play gif from file
    • Get next animation id
    • Reset next animation id
    • Send image animation
    • Send text animation
    • Clear all text area
    • Play buzzer
  • Batch APIs
    • Batching commands
    • Execute commands from url

Image Animation

Devices like Pixoo-64 supports play GIF file from file or even Internet directly, all we need is to specify a URL as below:

use divoom::*;

let pixoo = PixooClient::new("192.168.0.123");
pixoo.play_gif_file(DivoomFileAnimationSourceType::Url, "<Some URL goes here>").await?;

Text Animation

To create a text animation, we can use DivoomTextAnimation structure and send_text_animation API to help us:

use divoom::*;

let pixoo = PixooClient::new("192.168.0.123");
let animation = DivoomTextAnimation::default(); 
animation.text_string = "Foo".to_string();
pixoo.send_text_animation(animation).await?;

Command batching

In certain cases, we might want to run a lot of commands at the same time, such as initialize the settings. Pixoo devices supports batching all commands into a single request, but with only 1 single result being returned for indicating if everything succeeded or not.

Here is an example that we batch executed multiple commands to update the device settings:

use divoom::*;
let pixoo = PixooClient::new("192.168.0.123");
pixoo.start_batch()
  .set_device_rotation_angle(DivoomDeviceRotationAngle::Rotate90)
  .set_device_mirror_mode(DivoomDeviceMirrorMode::On)
  .set_device_brightness(30)
  .execute().await.expect("Request should succeed.");

Sending raw requests

In case new API is released and we haven't support it yet, or we need to do some experimental things by sending the raw payload, we can use the following API to send raw request directly, which works for both single request and batch mode.

Single request mode:

use divoom::*;

let pixoo = PixooClient::new("192.168.0.123");
pixoo.send_raw_request("{ \"Command\": \"Device/SetHighLightMode\", \"Mode\": 0 }").await?.expect("Request should succeed.");

Batch mode:

use divoom::*;
let pixoo = PixooClient::new("192.168.0.123");
pixoo.start_batch()
  .send_raw_request("{ \"Command\": \"Device/SetHighLightMode\", \"Mode\": 0 }".into())
  .execute_with_raw_response().await.expect("Request should succeed.");

Debugging

The debug logs are logged at debug level. Once we set the log level to debug, we will be able to start see it:

env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("debug")).init();

Or we can use RUST_LOG environment variable to change the level and enable the logs:

With the command tool (covered below soon), on windows:

> $env:RUST_LOG="debug"; .\divoom-cli.exe 192.168.0.123 channel get

And on linux:

RUST_LOG=debug ./divoom-cli.exe 192.168.0.123 channel get

Then we will see the output log like below:

[2022-07-10T00:33:50Z DEBUG divoom::clients::common::divoom_rest_client] Sending request: Url = "http://192.168.0.123/post", Body = "{"Command":"Channel/GetIndex"}"
[2022-07-10T00:33:50Z DEBUG reqwest::connect] starting new connection: http://192.168.0.123/
[2022-07-10T00:33:50Z DEBUG hyper::client::connect::http] connecting to 192.168.0.123:80
[2022-07-10T00:33:50Z DEBUG hyper::client::connect::http] connected to 192.168.0.123:80
[2022-07-10T00:33:50Z DEBUG hyper::proto::h1::io] flushed 107 bytes
[2022-07-10T00:33:50Z DEBUG hyper::proto::h1::io] parsed 2 headers
[2022-07-10T00:33:50Z DEBUG hyper::proto::h1::conn] incoming body is chunked encoding
[2022-07-10T00:33:50Z DEBUG hyper::proto::h1::decode] incoming chunked header: 0x22 (34 bytes)
[2022-07-10T00:33:50Z DEBUG reqwest::async_impl::client] response '200 OK' for http://192.168.0.123/post
[2022-07-10T00:33:50Z DEBUG divoom::clients::common::divoom_rest_client] Response header received: StatusCode = 200
[2022-07-10T00:33:50Z DEBUG hyper::proto::h1::conn] incoming body completed
[2022-07-10T00:33:50Z DEBUG hyper::client::pool] pooling idle connection for ("http", 192.168.0.123)
[2022-07-10T00:33:50Z DEBUG divoom::clients::common::divoom_rest_client] Response received: Body = "{"error_code": 0, "SelectIndex":3}"
CustomPage

To revert it back:

> $env:RUST_LOG="warn"; .\divoom-cli.exe 192.168.0.123 channel get
CustomPage

Command line tool

In order to help quickly give the APIs a try, we have also developed a command line tool. It also serves as an example on how to uses these APIs.

This tool is currently under construction and doesn't have all API covered yet.

Device discovery

> divoom-cli.exe discover
1 devices are found:
- Id = 300000001, Name = Pixoo, IP = 192.168.0.123

Devices APIs

# Check current channel
> .\divoom-cli.exe 192.168.0.123 channel get
Clock

# Check current clock
> .\divoom-cli.exe 192.168.0.123 channel get-clock
DivoomSelectedClockInfo { clock_id: 168, brightness: 67 }

# Create a text animation
> .\divoom-cli.exe 192.168.0.123 animation text set 1 "The gray fox jumped over the lazy dog"

# Play a gif from Internet
> .\divoom-cli.exe 192.168.0.123 animation gif play --url https://www.gifandgif.eu/animated_gif/Planets/Animated%20Gif%20Planets%20(16).GIF

# Send a raw request
#
# NOTICE: the double quotes in json string passed into the program needs to escaped with '\',
# otherwise, rust runtime (not structopt) will eat them before reaching main function, even we 
# pass the whole string as a string.
> .\divoom-cli.exe 192.168.0.164 raw '{\"Command\": \"Device/SetHighLightMode\", \"Mode\": 0}'

Help

> divoom-cli.exe
divoom-cli 0.1.0
r12f
https://github.com/r12f/divoom

USAGE:
    divoom-cli.exe [device-ip] <SUBCOMMAND>

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

ARGS:
    <device-ip>    Device IP. Required when using device APIs, such as "channel get".

SUBCOMMANDS:
    animation    Animation related APIs
    batch        Batch related APIs
    channel      Channel related APIs
    discover     Discover divoom devices by calling into divoom service API
    help         Prints this message or the help of the given subcommand(s)
    system       System/device related APIs
    tool         APIs to launch some tools

License

Apache-2.0: https://www.apache.org/licenses/LICENSE-2.0

You might also like...
Serde support for n-dimensional arrays from self-describing formats

serde-ndim Overview This crate provides a way to serialize and deserialize arrays of arbitrary dimensionality from self-described formats such as JSON

Extended Kinect support for Garry's Mod
Extended Kinect support for Garry's Mod

🦵 gmcl_rekinect This is a reimplementation of Kinect support for Garry's Mod, allowing you to do stuff like this on more platforms. Features Support

Rust 核心库和标准库的源码级中文翻译,可作为 IDE 工具的智能提示 (Rust core library and standard library translation. can be used as IntelliSense for IDE tools)

Rust 标准库中文版 这是翻译 Rust 库 的地方, 相关源代码来自于 https://github.com/rust-lang/rust。 如果您不会说英语,那么拥有使用中文的文档至关重要,即使您会说英语,使用母语也仍然能让您感到愉快。Rust 标准库是高质量的,不管是新手还是老手,都可以从中

A library for extracting #[no_mangle] pub extern "C" functions (https://docs.rust-embedded.org/book/interoperability/rust-with-c.html#no_mangle)

A library for extracting #[no_mangle] pub extern "C" functions In order to expose a function with C binary interface for interoperability with other p

Rust Imaging Library: A high-level Rust imaging crate.

ril Rust Imaging Library: A performant and high-level Rust imaging crate. Documentation • Crates.io • Discord What's this? This is a Rust crate design

Modern Rust utility library delivering modularity, performance & extras; or simply Rust version of Lodash

Lorust - API Documentation Lorust is the Rust version of Lodash, which is a modern Javascript utilty library delivering modularity, performance & extr

Rust library for hardware accelerated drawing of 2D shapes, images, and text, with an easy to use API.
Rust library for hardware accelerated drawing of 2D shapes, images, and text, with an easy to use API.

Speedy2D Hardware-accelerated drawing of shapes, images, and text, with an easy to use API. Speedy2D aims to be: The simplest Rust API for creating a

Shuttle is a library for testing concurrent Rust code

Shuttle Shuttle is a library for testing concurrent Rust code. It is an implementation of a number of randomized concurrency testing techniques, inclu

🦀 In progress Rust library for dogehouse.tv 🦀

dogehouse-rs WARNING: Still work in progress do not use yet Example In Cargo.toml dogehouse-rs = "*" In src/main.rs use dogehouse_rs::prelude::*; use

Comments
  • Added format and from_str for raw varient to dtos

    Added format and from_str for raw varient to dtos

    It turns out changing $dto_name:ty to $dto_name:ident makes rustc 😊

    here is what's being generated from the macro for ChannelType::Raw:

                    DivoomChannelType::Raw(n) => {
                        return {
                            let result = f.write_fmt(::core::fmt::Arguments::new_v1(
                                &[""],
                                &[::core::fmt::ArgumentV1::new_display(&n)],
                            ));
                            result
                        }
                    }
    

    Signed-off-by: Jiaxiao Zhou [email protected]

    opened by Mossaka 1
  • Add gateway api for controlling scenes

    Add gateway api for controlling scenes

    This will make the gateway becoming stateful essentially, because there is no way to reconcile the state with the device.

    It sucks, but for the simplicity, we will start with this and also use in-process memory store for now.

    opened by r12f 1
Releases(0.1.42)
Owner
Riff
blah...blah...blah...
Riff
Safe, idiomatic bindings to cFE and OSAL APIs for Rust

n2o4 The n2o4 crate provides safe, idiomatic Rust bindings to the APIs of cFE and OSAL, the libraries of the Core Flight System (cFS). IMPORTANT NOTE

null 3 Aug 29, 2022
A simple path traversal checker made with Rust. Useful for APIs that serve dynamic files.

Path trav A simple path traversal checker made with Rust. Useful for APIs that serve dynamic files. Note: this is a security tool. If you see somethin

Gátomo 3 Nov 21, 2022
The second Rust implementation on GitHub of third-party REST API client for Bilibili.

Bilibili REST API The second Rust implementation on GitHub of third-party REST API client for Bilibili. Designed to be lightweight and efficient. It's

null 4 Aug 25, 2022
🔥Implemetación de una API REST basada en microservicios con Rust

Microservicios ?? Breve Descripción Bienvenido a todos, aquí aprenderás a programar una API REST desde cero enfocada a la aquitectura de microservicio

Rust Latam Group 4 Dec 16, 2022
A backend framework for building fast and flexible APIs rapidly.

Andromeda Andromeda is a backend framework for Rust, to simplify the development of the kinds of basic API services that we developers have to build s

Framesurge 7 Dec 28, 2022
A Rust implementation of generic prefix tree (trie) map with wildcard capture support

prefix_tree_map A Rust implementation of generic prefix tree (trie) map with wildcard capture support. Design Trie is a good data structure for storin

EAimTY 3 Dec 6, 2022
a super fast scientific calculator with dimensional analysis support written in Rust 🦀

larvae a super fast scientific calculator with dimensional analysis support written in Rust ?? ?? heavily inspired from insect Usage: Command mode: $

John McAvoy 2 Jan 10, 2022
Rust based magic-string with source map chains support

enhanced-magic-string Rust implementation of https://www.npmjs.com/package/magic-string with original sourcemap chain support. license. This project i

Farm 3 Nov 5, 2023
Support SIMD low-memory overhead and high-performance adaptive radix tree.

Artful Artful is an adaptive radix tree library for Rust. At a high-level, it's like a BTreeMap. It is based on the implementation of paper, see The A

future 3 Sep 7, 2022
A tiny service that downloads files over HTTP links, with resume and restart support.

Http Drogue Http Drogue is a tiny service that downloads files over HTTP from links you provide. It can restart and resume interrupted downloads. Http

Kaan Barmore-Genç 4 Feb 27, 2023