How to return JSON array using bottle – minimal example

Returning a JSON array in bottle involves setting the response content type to application/json and then manually dumping the array using json.dumps():

#!/usr/bin/env python3
from bottle import route, run, response
import json

@route('/')
def json_array():
    response.content_type = 'application/json'
    return json.dumps(["a", "b", "c"])

run(host='localhost', port=9000)

 

Posted by Uli Köhler in Python

How to install entr on Ubuntu

entr is a utility to automatically restart a script if one or more files change.

Installing it on Ubuntu as is as easy as

sudo apt -y install entr

 

Posted by Uli Köhler in Linux

How to auto-restart bottle server when Python file changes using entr

Note: I do not recommend using entr any more since for me it doesn’t work reliably. I recommend using nodemon instead, see How to auto-restart bottle server when Python file changes using nodemon

Assuming you have a Python script server.py that you want to auto-reload every time the file changes, use the following script using entr:

ls *.py | entr python server.py

The ls *.py tells entr which files to watch for changes.

Posted by Uli Köhler in Python

Bottle HTTP server with dedicated server class – minimal example

This script uses a dedicated class MyServer to encapsulate the bottle server appropriately. Compared to our previous post Python bottle minimal example it provides better encapsulation of the server at the cost of slightly more lines of code.

#!/usr/bin/env python3
from bottle import Bottle, run

class MyServer(object):
    def __init__(self):
        self.app = Bottle()
        self.init_routes()
        
    def init_routes(self):
        """Initialize all routes"""
        @self.app.route('/hello')
        def hello():
            return "Hello World!"

    def run(self):
        run(self.app, host='0.0.0.0', port=8080)
        
# Example usage
if __name__ == "__main__":
    server = MyServer()
    server.run()

How to use

Run the server

python bottle-server.py

and open

http://localhost:8080/hello

Now you should see the Hello World! message.

Posted by Uli Köhler in Python

Inventree Python API: How to list all stock locations

See our previous post Inventree Python API: Minimal API connect example using YAML config for our method of creating the api object using a YAML config file!

from inventree.stock import StockLocation

all_stock_locations = StockLocation.list(api)

# Dict of part categories by name
# (e.g. 'OpAmps')
stock_locations_by_name = {
    category["name"]: category
    for category in all_stock_locations
}
# Dict of part categories by public key (e.g. 7)
part_locations_by_pk = {
    category.pk: category
    for category in all_stock_locations
}
# Dict of part categories by hierarchical path
# (e.g. 'Office/Spart parts box')
stock_locations_by_pathstring = {
    category.pathstring: category
    for category in all_stock_locations
}

 

Posted by Uli Köhler in InvenTree, Python

How to manually run InvenTree backup

By default, InvenTree creates a daily backup of both its data files and the database.

You can manually run the backup by using the following command

invoke backup

In a docker-compose-based setup, for example, you can run the backup using

docker-compose run inventree-server invoke restore

Example output:

Loading config file : /home/inventree/data/config.yaml
InvenTree translation coverage: 22%
Restoring InvenTree database...
Finding latest backup
Restoring backup for database 'default' and server 'None'
Restoring: default-de1837564ff0-2023-01-20-004732.psql.bin.gz
Restore tempfile created: 391.4 KiB
Restoring InvenTree media files...
Restoring backup for media files
Finding latest backup
Restoring: de1837564ff0-2023-01-20-004736.tar.gz

 

Posted by Uli Köhler in InvenTree

Which PostgreSQL version to use for InvenTree?

At the time of writing this post (2022-01-20), InvenTree only support PostgreSQL version 11, 12 & 13.

Newer versions of PostgreSQL such as version 14 and 15 are not supported due to dependencies in the backup workflow.

Source: This reddit post

Posted by Uli Köhler in InvenTree

How to access InvenTree backup settings?

In order to access InvenTree’s backup settings, you can go straight to it using

https://inventree.mydomain.com/admin/django_q/schedule/8

or accessing it by opening Admin, then Scheduled tasks and then searching for backup and opening the

InvenTree.tasks.run_backup

task.

By default, InvenTree will perform a full backup daily.

Posted by Uli Köhler in InvenTree

Inventree Python API: How to create a new part

See our previous post Inventree Python API: Minimal API connect example using YAML config for our method of creating the api object using a YAML config file!

The following code finds a part category called ICs and creates a new part in that category.

First, we need to fetch the part categories, this is from our previous post Inventree Python API: Minimal API connect example using YAML config:

from inventree.part import PartCategory

all_categories = PartCategory.list(api)

# Dict of part categories by name
# (e.g. 'OpAmps')
part_categories_by_name = {
    category["name"]: category
    for category in all_categories
}
# Dict of part categories by public key (e.g. 7)
part_categories_by_pk = {
    category.pk: category
    for category in all_categories
}
# Dict of part categories by hierarchical path
# (e.g. 'Electronics-Components/ICs/OpAmps')
part_categories_by_pathstring = {
    category.pathstring: category
    for category in all_categories
}

Now let’s select the correct category:

ics = part_categories_by_name['ICs']

Now it’s finally time to create the part:

from inventree.part import Part

new_part = Part.create(api, {
    'name': 'L78L33ABD',
    'description': '100mA 3.3V fixed LDO regulator, SOIC-8',
    'category': ics.pk
})

You can read the primary key (pk) for the newly generated part using

new_part.pk
Posted by Uli Köhler in InvenTree, Python

Inventree Python API: How to list all part categories

See our previous post Inventree Python API: Minimal API connect example using YAML config for our method of creating the api object using a YAML config file!

from inventree.part import PartCategory

all_categories = PartCategory.list(api)

# Dict of part categories by name
# (e.g. 'OpAmps')
part_categories_by_name = {
    category["name"]: category
    for category in all_categories
}
# Dict of part categories by public key (e.g. 7)
part_categories_by_pk = {
    category.pk: category
    for category in all_categories
}
# Dict of part categories by hierarchical path
# (e.g. 'Electronics-Components/ICs/OpAmps')
part_categories_by_pathstring = {
    category.pathstring: category
    for category in all_categories
}

Note that this code by itself does not take into account the hierarchy of the categories.

Example output

part_categories_by_name:

{'Elektronik-Komponenten': <inventree.part.PartCategory at 0x7fd735125510>,
 'ICs': <inventree.part.PartCategory at 0x7fd7356d1720>,
 'OpAmps': <inventree.part.PartCategory at 0x7fd735ead4e0>}

part_categories_by_pk:

{1: <inventree.part.PartCategory at 0x7fd7346b5db0>,
 2: <inventree.part.PartCategory at 0x7fd73438aa10>,
 3: <inventree.part.PartCategory at 0x7fd727325b40>}

part_categories_by_pathstring:

{'Elektronik-Komponenten': <inventree.part.PartCategory at 0x7fd727bd3040>,
 'Elektronik-Komponenten/ICs': <inventree.part.PartCategory at 0x7fd727bd1db0>,
 'Elektronik-Komponenten/ICs/OpAmps': <inventree.part.PartCategory at 0x7fd727bd1060>}

 

Posted by Uli Köhler in InvenTree, Python

Inventree Python API: Minimal API connect example using YAML config

This example allows you to create a config file inventree.yml:

server: 'https://inventree.mydomain.com'
username: 'admin'
password: 'Chuiquu5Oqu8il5ahLoja4aecai4ee'

and then read it in Python and connect to the Inventree API:

from inventree.api import InvenTreeAPI

# Load config
import yaml

with open("inventree.yml", "r") as file:
    config = yaml.safe_load(file)
    
api = InvenTreeAPI(config["server"], username=config["username"], password=config["password"])

 

Posted by Uli Köhler in InvenTree, Python

How to print WiFi MAC address to serial on ESP32 (Arduino)?

It’s as simple as

Serial.println(WiFi.macAddress());

Full example

#include <Arduino.h>

void setup() {
    Serial.begin(115200);
    Serial.println(WiFi.macAddress());
}

void loop() {
    // ...
}

 

Posted by Uli Köhler in Arduino, ESP8266/ESP32

How to get WiFi MAC address as binary on the ESP32 (Arduino)?

uint8_t mac[6];
WiFi.macAddress(mac);

 

Posted by Uli Köhler in Arduino, ESP8266/ESP32, Networking

VirtualHere USB server & systemd autostart on Raspberry Pi in 15 seconds

The following script will download the VirtualHere USB server for the Raspberry Pi (generic version for ARM) and create a systemd service called vhusbd.service.

In case you are not using the Raspberry Pi, see the VirtualHere server download page to obtain.

#!/bin/bash
# This script installs and enables/starts the VirtualHere USB server
wget -O /usr/bin/vhusbd https://www.virtualhere.com/sites/default/files/usbserver/vhusbdarm
chmod a+x /usr/bin/vhusbd

cat >/etc/systemd/system/vhusbd.service <<EOF
[Unit]
Description=vhusbd
After=network-online.target

[Service]
Restart=always
User=root
Group=root
ExecStart=/usr/bin/vhusbd

[Install]
WantedBy=multi-user.target
EOF

# Enable and start service
systemctl enable --now vhusbd.service

 

Posted by Uli Köhler in Embedded, Raspberry Pi

How read STM32 HRTIM master timer current counter value

The STM32 HRTIM (high resolution timer) provides a high speed counter that is suitable for benchmarks due to its high counting frequency of up to 240 MHz on the STM32H743.

You can read its current counter value using

uint32_t t0 = HRTIM1->sMasterRegs.MCNTR;

 

Posted by Uli Köhler in STM32

How to determine how many percent of memory (heap) are free on ESP32?

This approach works for Arduino / PlatformIO as well as ESP-IDF projects.

#include <esp_heap_caps.h>

uint32_t freeHeapBytes = heap_caps_get_free_size(MALLOC_CAP_DEFAULT);
uint32_t totalHeapBytes = heap_caps_get_total_size(MALLOC_CAP_DEFAULT);
float percentageHeapFree = freeHeapBytes * 100.0f / (float)totalHeapBytes;

// Print to serial
Serial.printf("[Memory] %.1f%% free - %d of %d bytes free\n", percentageHeapFree, freeHeapBytes, totalHeapBytes);

Also see How to find number of free bytes in ESP32 memory / heap?

Posted by Uli Köhler in ESP8266/ESP32

How to find number of free bytes in ESP32 memory / heap?

This approach works for Arduino / PlatformIO as well as ESP-IDF projects.

#include <esp_heap_caps.h>

uint32_t freeHeapBytes = heap_caps_get_free_size(MALLOC_CAP_DEFAULT);

 

Posted by Uli Köhler in ESP8266/ESP32

How to use vPortGetHeapStats() on the ESP32?

Problem:

You see an error message like the following one while compiling your ESP32 project

src/main.cpp:128:3: error: 'vPortGetHeapStats' was not declared in this scope
   vPortGetHeapStats(&heapStats);

Solution:

Although vPortGetHeapStats() is typically defined in freertos/portable.h, you can not use   vPortGetHeapStats() on the ESP32 since the frameworks do not use the FreeRTOS heap implementation.

In order to find informatio about heap usage, use the ESP heap API such as esp_get_free_heap_size().

Posted by Uli Köhler in ESP8266/ESP32, FreeRTOS

What caps argument to give to ESP32 heap_caps_…() functions?

Almost all of the ESP32 heap_caps_...() functions take a uint32_t caps argument.

In case you just want to have general information about the heap, use

MALLOC_CAP_DEFAULT

as an argument.

Most applications will rarely use any other value than MALLOC_CAP_DEFAULT. Other values which are used semi-frequently include:

  • MALLOC_CAP_SPIRAM
  • MALLOC_CAP_INTERNAL (memory must not be located in SPI RAM)
For more details on how the memory of the ESP32 is organized, see the official documentation.
Posted by Uli Köhler in ESP8266/ESP32
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPTPrivacy &amp; Cookies Policy