Tag Archives: python

I asked ChatGPT to write code for a Crack the Code game.

The Game

elcome to Crack the Code!
The code has 4 digits. Each digit is between 0 and 9.
You have 10 tries to guess the code.
After each guess, you will be told how many digits you got correct and how many were misplaced.
Good luck!
Enter your guess: 1234
Guess 1: 1234 - 0 correct, 0 misplaced
Enter your guess: 5678
Guess 2: 5678 - 2 correct, 1 misplaced
Enter your guess: 5689
Guess 3: 5689 - 1 correct, 2 misplaced
Enter your guess: 9688 
Guess 4: 9688 - 1 correct, 2 misplaced
....
Sorry, you did not crack the code. The code was 5568.

Generated python code

import random

def generate_code():
    code = ""
    for i in range(4):
        code += str(random.randint(0, 9))
    return code

def check_guess(code, guess):
    correct_digits = 0
    misplaced_digits = 0
    for i in range(4):
        if guess[i] == code[i]:
            correct_digits += 1
        elif guess[i] in code:
            misplaced_digits += 1
    return (correct_digits, misplaced_digits)

def play_game():
    print("Welcome to Crack the Code!")
    print("The code has 4 digits. Each digit is between 0 and 9.")
    print("You have 10 tries to guess the code.")
    print("After each guess, you will be told how many digits you got correct and how many were misplaced.")
    print("Good luck!")
    code = generate_code()
    num_guesses = 0
    while num_guesses < 10:
        guess = input("Enter your guess: ")
        if len(guess) != 4 or not guess.isdigit():
            print("Invalid input. Please enter a 4-digit number.")
            continue
        num_guesses += 1
        correct, misplaced = check_guess(code, guess)
        print(f"Guess {num_guesses}: {guess} - {correct} correct, {misplaced} misplaced")
        if correct == 4:
            print("Congratulations! You cracked the code!")
            return
    print(f"Sorry, you did not crack the code. The code was {code}.")

play_game()

After this i let the AI made some changes, which kinda worked.
Scary nevertheless

Python Baudot code for Wemos Matrix Led

I wrote a python script to generate binary data to include in my Arduino sketch.
This Arduino displays codes send though MQTT.

https://en.wikipedia.org/wiki/Baudot_code

CODE:

python3 matrix.py apple gives me

byte apple_Char[8] = {
  0b00000000,
  0b01000100,
  0b01111000,
  0b00000000,
  0b00110000,
  0b00000000,
  0b00111000,
  0b00000000
};

Python Code
import sys

a = [ 
        [0,0,0,0,0,0,0,0 ], 
        [0,0,0,0,0,0,0,0 ], 
        [0,0,0,0,0,0,0,0 ], 
        [0,0,0,0,0,0,0,0 ], 
        [0,0,0,0,0,0,0,0 ], 
        [0,0,0,0,0,0,0,0 ], 
        [0,0,0,0,0,0,0,0 ], 
        [0,0,0,0,0,0,0,0 ] 
    ] 

letters = [
        [0,1,1,0,0,0,0,0 ],
        [0,1,0,0,0,1,1,0 ],
        [0,0,1,0,1,1,0,0 ],
        [0,1,0,0,0,1,0,0 ],
        [0,1,0,0,0,0,0,0 ],
        [0,1,0,0,1,1,0,0 ],
        [0,0,1,0,0,1,1,0 ],
        [0,0,0,0,1,0,1,0 ],
        [0,0,1,0,1,0,0,0 ],
        [0,1,1,0,0,1,0,0 ],
        [0,1,1,0,1,1,0,0 ],
        [0,0,1,0,0,0,1,0 ],
        [0,0,0,0,1,1,1,0 ],
        [0,0,0,0,1,1,0,0 ],
        [0,0,0,0,0,1,1,0 ],
        [0,0,1,0,1,0,1,0 ],
        [0,1,1,0,1,0,1,0 ],
        [0,0,1,0,0,1,0,0 ],
        [0,1,0,0,1,0,0,0 ],
        [0,0,0,0,0,0,1,0 ],
        [0,1,1,0,1,0,0,0 ],
        [0,0,1,0,1,1,1,0 ],
        [0,1,1,0,0,0,1,0 ],
        [0,1,0,0,1,1,1,0 ],
        [0,1,0,0,1,0,1,0 ],
        [0,1,0,0,0,0,1,0 ]
        ]

number=0
word=str(sys.argv[1])

for col in range(len(word)) :
    character=word[col]

    number = ord(character) - 97
    nextcol = col + 1
    for row in range(len(a[col])) :
        a[row][nextcol] = letters[number][row]


print("byte " + word + "_Char[8] = {")
for i in range(len(a)) : 
    print("  0b", end = '')
    for j in range(len(a[i])) : 
        print(a[i][j], end="")   
    if i < 7:
        print(",")
print()
print("};")

Arduino test code

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <WiFiClient.h>


#include "WEMOS_Matrix_LED.h"
MLED mled(5); //set intensity=5

const char* wifi_ssid = "MYSSID"; // Enter your WiFi name
const char* wifi_password =  "MYSSIDPASS"; // Enter WiFi password
const char* mqtt_server = "MYMQTTSERVER";
const int mqtt_port = 1883;
const char* mqttUser = "";
const char* mqttPassword = "";
#define MSG_BUFFER_SIZE  (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

WiFiClient espClient;

PubSubClient mqtt(espClient);

void setup_wifi() {
  delay(10);
  WiFi.mode(WIFI_STA);
  WiFi.begin(wifi_ssid, wifi_password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
}
 
byte clear_Char[8] = {  
  0b00000000,
  0b00000000,
  0b00000000,
  0b00000000,
  0b00000000,
  0b00000000,
  0b00000000,
  0b00000000
};
 
byte baudot_Char[8] = {
  0b11111111,
  0b01101010,
  0b00011100,
  0b11111111,
  0b00110100,
  0b00010000,
  0b00000100,
  0b11111111  
};
 

 
#define TIME 500
 
void setup() { 
    Serial.begin(115200);
      setup_wifi();
        mqtt.setServer(mqtt_server, mqtt_port);

WiFiClient espClient;
PubSubClient mqtt(espClient);

  mqtt.setClient(espClient);
  mqtt.setServer(mqtt_server, mqtt_port);
      delay(500);

  mqtt.subscribe("escape/matrixledin");
        delay(500);

  mqtt.setCallback(callback);

  }

void callback(char* topic, byte* payload, unsigned int length) {
        Serial.println("callback");
    String topicStr = topic;
      byte value = atoi((char*)payload);
        snprintf (msg, MSG_BUFFER_SIZE, "%1d", value);

              mqtt.publish("escape/matrixledout", msg);
       if (value == 1){

drawChar(baudot_Char); 

 }else if (value == 0){
  drawChar(cleat_Char); 
  }else if (value == 2){
  drawChar(test_Char); 
  }else if (value == 3){
  drawChar(no_Char); 
 }
 }

void reconnect() {

  while (!mqtt.connected()) {
    String clientId = "matrixClient-";
    clientId += String(random(0xffff), HEX);
    if (mqtt.connect(clientId.c_str())) {
      mqtt.publish("escape/outTopic", "hello from 8x8led module");
                Serial.println("resubscribe");

      mqtt.subscribe("escape/matrixledin");
        mqtt.setCallback(callback);

    } else {
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
 
void loop() {

 if (!mqtt.connected()) {
          Serial.println("reconnect called");
    reconnect();
  }
    mqtt.loop();

}
 
void drawChar(byte character[8]) {
  for(int y=7;y>=0;y--) {
  for (int x=0; x <= 7; x++) { 
    if (character[(7-y)] & (B10000000 >> x)) {
     mled.dot(x,y); // draw dot
    } else {
     mled.dot(x,y,0);//clear dot
    }
  }
  mled.display();  
  }
}

Playing with lasercutter steppermotors

Busy day: I’ve airbrushed some 3D pieces a few days ago, but i need 50 or so more.
Meanwhile is was reinstalling octoprint, and making a new version of my Bluetooth page flipper. (Android Music Sheet Pedal Thingy. Which i also didn’t post apparently)
But the main project was this:

I was curious how fast the stepper motors are on my laser cutter. And for what can we utilize this!

So I took a Raspberry Zero and some rotary encoders, lets make an etch-a-sketch like thingy.


Some rotary encoder modules I had.

Next to do: 3D print a pen holder, and alter the code to enable the laser when moving!

CODE

Below code uses a simple rotary class, and generates control GCodes for the steppers/Sculpfun

import time
import serial
import RPi.GPIO as GPIO
from encoder import Encoder

def valueChanged(value, direction):
    print("* New value: {}, Direction: {}".format(value, direction))

GPIO.setmode(GPIO.BCM)

e1 = Encoder(20, 21, valueChanged)
e2 = Encoder(16, 12, valueChanged)

x = 0
y = 0
arduino = serial.Serial('/dev/ttyUSB0', 115200, timeout=.1)

newx = 0
mystringx = ""
newy = 0
mystringy = ""

arduino.write(str.encode("G00 G17 G40 G21 G54\r\n"))
arduino.write(str.encode('G90\r\n'))
arduino.write(str.encode('M4\r\n'))
arduino.write(str.encode('M8\r\n'))
arduino.write(str.encode('G0 X41.5Y36.05\r\n'))
arduino.write(str.encode('M3\r\n'))
#arduino.write(str.encode('G91\r\n'))
arduino.write(str.encode('G1 X2.5F6000S0\r\n'))
arduino.write(str.encode('G1 X0\r\n'))
arduino.write(str.encode('G1 Y0\r\n'))

try:
    while True:
        data = arduino.readline()[:-2] #the last bit gets rid of the new-line chars
        if data:
                print (data)
        arduino.write(str.encode("G1 F10000\r\n"))
        newx=e1.getValue() *5 + 100
        newy=e2.getValue() *5 + 100
        mystringx=f"G1 X{newx}\r\n"
        mystringy=f"G1 Y{newy}\r\n"
#        print(mystringx)
        arduino.write(str.encode(mystringx))
        arduino.write(str.encode(mystringy))

except Exception:
    pass

GPIO.cleanup()

Movie to txt in dutch

In the past i’ve converted some VHS movies speech to text, using all kinds of tools.
Lets use some opensource tools!

pip install moviepy
pip install SpeechRecognition

Create a python script with the following:
(Called mine wav2txt.py)

import math, contextlib
import speech_recognition as sr
from moviepy.editor import AudioFileClip
movie_audio_file_name = "movieadiofile.wav"
with contextlib.closing(wave.open(movie_audio_file_name,'r')) as f:
    frames = f.getnframes()
    rate = f.getframerate()
    duration = frames / float(rate)
total_duration = math.ceil(duration / 60)
r = sr.Recognizer()
for i in range(0, total_duration):
    with sr.AudioFile(movie_audio_file_name) as source:
        audio = r.record(source, offset=i*60, duration=60)
    f = open("transcription.txt", "a")
    f.write(r.recognize_google(audio, language="nl-NL"))
    f.write(" ")
f.close()

Now convert a movie to wav using below.

ffmpeg -i /fileserver/path/koolhoven.mkv movieaudiofile.wav

run python3 wav2txt.py

output
(Note .. these are not timestamped for subtitles)
I only needed the things being said in the home movie recordings as text.

Ik zit hier in de film The James Dean aan de
wereld voorstelde en daarmee de tienerfilm ingeleverd introduceren zelden werden onrustige 10 asiel zo mooi blootgelegd als ik deze film van Nicolas bij en dat wordt dan meteen toevallig even de mooiste
titels ooit wel eens autocross vanavond kijken we naar de kom ik nog even veel zomer dat je voor het eerste meisje Zoem de eerste baantje

etc..

Raspberry Zero with display

I’ve installed a headless Raspbian on a Pi Zero with a 2×16 Chars lcd display. As part of the Escape Room over the internet

Using the raspberry imager:
I’ve set the username/password and ssh access in this tool.
For wifi access i’ve placed below file on the SDcard in /boot
(You can do this in the tool, but i want to make this dynamic when connected at a remote site.)
file: wpa_supplicant.conf

country=NL
update_config=1
ctrl_interface=/var/run/wpa_supplicant

network={
 scan_ssid=1
 ssid="MYSSID"
 psk="MYSSIDPASS"
}

ssh into the RPi

sudo raspi-config
Interface options and enable I2C

sudo apt-get install python3-smbus

wget https://gist.githubusercontent.com/DenisFromHR/cc863375a6e19dce359d/raw/36b82e787450d127f5019a40e0a55b08bd43435a/RPi_I2C_driver.py
and 
wget https://gist.githubusercontent.com/DenisFromHR/cc863375a6e19dce359d/raw/36b82e787450d127f5019a40e0a55b08bd43435a/examples.py

For python3 edit the example and put at the top

# requires RPi_I2C_driver.py
import RPi_I2C_driver
from time import *
unichr = chr

Run with 
python3 examples.py
lcd display with i2c backpack
I2C backpack

Below is a mockup session.

Next todo:

  • Add more hardware (like buttons) to the RPI
  • Configure an Accesspoint on this Rpi for other devices to connect to
  • Install a local Mqtt broker, which connects secure to my internet facing broker
Setup example

Radar module RCWL-0516 with MQTT

RCWL-0516 module (radar)

Last year i was playing with this radar module also, but today i made a version with MQTT and a linux client.
(There is a project on the internet which uses a HC-SR04, and a arduino connected to the Laptop. This setup is more sensitive and no need for a usb thinghy.)

HC-SR04 module (ultrasound)

Last years version, using a micro transformer and a ESP-12

When using MQTT i can integrate this in HomeAssistant, Domoticz, NodeRed and more.
But i’ve written a python script which runs on my Laptop.
For example i can: Kill vlc, change to my work desktop, stop sound output and lock the screen. (everything you can script)

I wanted to have a “mobile” version of the sensor so i can place it anywhere. (Frontdoor, gardengate, candydrawer 🙂 )

These modules are very cheap, but do their job well!

I’ve used a Wroom ESP32 and a BattBorg together with the module, that’s it.

Simplified schematic (without the battborg)

I’m using PIN34 as an analog input.

Radar module pins:

  • CDS not used
  • VIN 5V power
  • OUT 0-3.3V signal (analog)
  • GND
  • 3v3 not used

Arduino sketch

#include <WiFi.h>
#include <PubSubClient.h>
#include <Wire.h>

const char* ssid = "MYSSID";
const char* password = "MYPASS";
const char* mqtt_server = "IP-MQTT-SERVER";
const char* mqtt_username = "";
const char* mqtt_password = "";
const char* clientID = "radar";

const int tiltPin = 34;
int tiltState = 0;    
int previousState = 0;   

WiFiClient espClient;

PubSubClient client(espClient);

String translateEncryptionType(wifi_auth_mode_t encryptionType) {
 
  switch (encryptionType) {
    case (WIFI_AUTH_OPEN):
      return "Open";
    case (WIFI_AUTH_WEP):
      return "WEP";
    case (WIFI_AUTH_WPA_PSK):
      return "WPA_PSK";
    case (WIFI_AUTH_WPA2_PSK):
      return "WPA2_PSK";
    case (WIFI_AUTH_WPA_WPA2_PSK):
      return "WPA_WPA2_PSK";
    case (WIFI_AUTH_WPA2_ENTERPRISE):
      return "WPA2_ENTERPRISE";
  }
}
 
void scanNetworks() {
   int numberOfNetworks = WiFi.scanNetworks();
   Serial.print("Number of networks found: ");
  Serial.println(numberOfNetworks);
   for (int i = 0; i < numberOfNetworks; i++) {
 
    Serial.print("Network name: ");
    Serial.println(WiFi.SSID(i));
 
    Serial.print("Signal strength: ");
    Serial.println(WiFi.RSSI(i));
 
    Serial.print("MAC address: ");
    Serial.println(WiFi.BSSIDstr(i));
 
    Serial.print("Encryption type: ");
    String encryptionTypeDescription = translateEncryptionType(WiFi.encryptionType(i));
    Serial.println(encryptionTypeDescription);
    Serial.println("-----------------------");
 
  }
}
 
void connectToNetwork() {
  WiFi.begin(ssid, password);
   while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Establishing connection to WiFi..");
  }
   Serial.println("Connected to network");
 }

void reconnect() {
  while (!client.connected()) {
    if (client.connect(clientID, mqtt_username, mqtt_password)) {
    } else {
      delay(2000);
    }
  }
}
void setup()
{
  {
    Serial.begin(115200);
    scanNetworks();
    connectToNetwork();
    Serial.println(WiFi.macAddress());
    Serial.println(WiFi.localIP());
    client.setServer(mqtt_server, 1883);
    pinMode(tiltPin, INPUT);
  }
}
void loop() {
  tiltState = analogRead(tiltPin);
    if (tiltState < 3048) {
      client.publish("radar/state", "0"); //
    } else {
      client.publish("radar/state", "1"); //
    }
     delay(100);
   {
    if (!client.connected()) {
      reconnect();
    }
    client.loop();
  }
}

Lockscreen!

Below shows the speed of detection, and sending though the network

Python script which does a lock-screen using XDOTOOL

from paho.mqtt import client as mqtt_client
import subprocess
import time

broker = 'MQTT-SERVER'
port = 1883
topic = "radar/state"
client_id = "radarclient"

def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client

def subscribe(client: mqtt_client):
    def on_message(client, userdata, msg):
        state = msg.payload.decode()
        print (state)
        if state == "1":
            subprocess.Popen(["xdotool","key","Super_L+l"])
            time.sleep(30)


    client.subscribe(topic)
    client.on_message = on_message

def run():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()

if __name__ == '__main__':
    run()

change
subprocess.Popen([“xdotool”,”key”,”Super_L+l”])
into
subprocess.Popen([“switchdesktop”])
to run a script named switchdesktop

#!/bin/bash
# This is the switchdesktop script, it goes to the next screen using winows-page-down combo
xdotool key "Super_L+Page_Down"

Todo:

3D print a case
Make a version which becomes a Access Point.
Then make another arduino setup which controls my Nikon.
So it can act like a wildcam (offline)

Something like below, using a optocoupler ( i still got some leftovers from my doorbell to gpio-pin project.)

Glade and python – network tester

THIS IS A WORK IN PROGRESS ! .. Updates follow

UPDATE: Found a glade project from 2002
https://www.henriaanstoot.nl/2002/02/20/reverse-engineering-a-alpha-ticker-led-scoller/

The goal of this project is to have a raspberry-pi with a screen wich shows network information.
It wil be using a battery, touchscreen .. maybe some status leds.
When debugging network issues we want to have information when/if/how a network port works on our switches.

It should show:

  • dhcp ip
  • gateway
  • can access internet?
  • speedtest
  • detect if vlan tagged network packets are present on the port?
  • icmp test
  • list of detected nearby hosts?

A long time ago i played with glade and C / Perl.

But i’d rather use python so i’m looking into glade/python combi for this little project.

Glade is a gnome/GTK user interface RAD tool. (Rapid Application Development)

i’ve used zenity and yad before to create simple gui’s for bash scripts, these where only for quick and dirty solutions. (See other posts)
Glade is a far better solution, but a little harder to use.

Below is a little framework i started with

Python script

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

class Handler:
    def onDestroy(self, *args):
        Gtk.main_quit()

    def on_firstbutton_clicked(self, button):
        print("Ping test")

builder = Gtk.Builder()
builder.add_from_file("mytest.glade")
builder.connect_signals(Handler())

window = builder.get_object("Main")
window.show_all()

Gtk.main()

Glade file

<?xml version="1.0" encoding="UTF-8"?>
<!-- Generated with glade 3.38.2 -->
<interface>
  <requires lib="gtk+" version="3.20"/>
  <object class="GtkWindow" id="Main">
    <property name="can-focus">False</property>
    <property name="title" translatable="yes">Networktool</property>
    <property name="default-width">440</property>
    <property name="default-height">250</property>
    <property name="icon-name">network-wired</property>
    <child>
      <object class="GtkFixed" id="fixed1">
        <property name="visible">True</property>
        <property name="can-focus">False</property>
        <child>
          <object class="GtkButton" id="firstbutton">
            <property name="label" translatable="yes">Ping test</property>
            <property name="width-request">100</property>
            <property name="height-request">16</property>
            <property name="visible">True</property>
            <property name="can-focus">True</property>
            <property name="receives-default">True</property>
            <signal name="clicked" handler="on_firstbutton_clicked" swapped="no"/>
          </object>
          <packing>
            <property name="x">56</property>
            <property name="y">40</property>
          </packing>
        </child>
        <child>
          <object class="GtkButton" id="speedtest">
            <property name="label" translatable="yes">Speed test</property>
            <property name="width-request">100</property>
            <property name="height-request">16</property>
            <property name="visible">True</property>
            <property name="can-focus">True</property>
            <property name="receives-default">True</property>
          </object>
          <packing>
            <property name="x">56</property>
            <property name="y">89</property>
          </packing>
        </child>
        <child>
          <object class="GtkTextView">
            <property name="width-request">179</property>
            <property name="height-request">166</property>
            <property name="visible">True</property>
            <property name="can-focus">True</property>
          </object>
          <packing>
            <property name="x">222</property>
            <property name="y">36</property>
          </packing>
        </child>
      </object>
    </child>
  </object>
</interface>

Which is generated using the Glade designer

When running you get below screen

Old glade program (2003)

Energy bill and ledserver

Having a lot of devices and running a Lab wil use a lot of energy. Now with the energy crisis in Europe, i had to take a closer look at whats using power in my house.

I notished some weird usage patterns while measuring.

I’m using a few shelly power plugs, to measure devices and powerstrips.

With these devices you can control devices connected to it.
On/Off/Timer etcetera.
It wil measure the power usage in watts, and it even got a temperature sensor.
I like the fact that it perfectly integrates into your home automation using an extensive API.
curl commands to controll, and even MQTT messaging. Intergrating in Home Assistant is a breeze.

So i was monitoring a bunch of stuff using Nodered/Grafana/Homeassistant and saw some recurring usage.
But being always late to check things, i made use of my ledserver i’ve build a long time ago.

This ledserver consists of a Raspberry Pi Zero, with a led string and a API written in python.

Below is autostarted on the Raspberry

( I made this ledserver for work, it showed the status of servers and services. Beside that every colleage had a range which he could use for his own scripts. I made some little bash script templates to have led funtions standard in your bash profile.

#!/usr/bin/python


# apt-get install python-flask
#

import Adafruit_WS2801
import Adafruit_GPIO.SPI as SPI
import struct

from flask import Flask, render_template, request
app = Flask(__name__)

PIXEL_COUNT = 32
SPI_PORT   = 0
SPI_DEVICE = 0

pixels = Adafruit_WS2801.WS2801Pixels(PIXEL_COUNT, spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

pixels.clear()
pixels.show()

@app.route("/led/<deviceName>/<color>")
def action(deviceName, color):
        if deviceName == 'reset':
                print ("reset")
                pixels.clear()
        print (deviceName)
        led = int(deviceName)
        s = color
        r = int(s[ :2], 16)
        b = int(s[2:4], 16)
        g = int(s[4: ], 16)

        pixels.set_pixel_rgb(led, r,g,b)
        pixels.show()

        templateData = {
                'rled'  : r,
                'bled'  : b,
                'gled'  : g,
                'deviceName'  : deviceName,
        }
        return render_template('index.html', **templateData)

@app.route("/control/<controlcommand>")
def actioncommand(controlcommand):
        if controlcommand == 'clear':

                print("clear")
                pixels.clear()
                pixels.show()

        templateData = {
                'controlcommand'  : controlcommand,
        }
        return render_template('index.html', **templateData)

@app.route("/range/<start>/<stop>/<color>")
def rangecommand(start,stop,color):
        s = color
        r = int(s[ :2], 16)
        b = int(s[2:4], 16)
        g = int(s[4: ], 16)
        startled = int(start)
        stopled = int(stop)
        while (startled < stopled):
          pixels.set_pixel_rgb(startled, r,g,b)
          startled=startled + 1
        pixels.show()

        templateData = {
                'rangecommand'  : rangecommand,
        }


        return render_template('index.html', **templateData)



if __name__ == "__main__":
   app.run(host='0.0.0.0', port=8080, debug=True)

Now you can control the leds with a simple curl command:

curl http://ledserver:8080/range/startled/endled/colorinrgb
curl http://ledserver:8080/led/lednumber/colorinrgb
curl http://ledserver:8080/control/clear

So today i made a little script to show power usage.

I’m reading the current power usage from a LS120 Youless

Youless LS120 device, which you can connect to your P1 connector.

With below bash script i’m reading the webinterface and update the ledstring.
I was using this ledserver for general notification usage. Below a 2 minute hack ..

#!/bin/bash
while true; do
number=$(echo $(curl -s http://youlessip/a | grep Watt | head -1 | awk '{ print $1 }') / 100  | bc)
curl -s http://ledserver:8080/control/clear
curl -s http://ledserver:8080/range/00/$number/010101
sleep 10
done
Using 9 leds = 9xx watt

Memory map generator

Started to write a program to generate a memory map like this

It will be a python script which generates a ascii table.

| a15 | a14 | a13 | a12 | a11 | a10 | a09 | a08 | a07 | a06 | a05 | a04 | a03 | a02 | a01 | a00 |
|  1  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  | ROM
|  0  |  0  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  | RAM
|  0  |  1  |  1  |  x  |  x  |  x  |  x  |  x  |  x  |  x  |  x  |  x  |  a  |  a  |  a  |  a  | VIA
|  0  |  0  |  0  |  0  |  0  |  0  |  0  |  1  |  a  |  a  |  a  |  a  |  a  |  a  |  a  |  a  | PS

Above example shows:

  • Rom – $8000 and up
  • Ram – $0000 till $3FFF
  • Via chip – $6xxx-$7xxxx 16 addresses repeating in this block.
    This will be the interesting/hard part
  • Program stack – in RAM – $0100-$01FF

Generated output

| 0000 | ram |     |     |      |      |
| 00ff | ram |     |     |      |      |
| 0100 | ram |     | ps  |      |      |
| 01ff | ram |     | ps  |      |      |
| 0200 | ram |     |     |      |      |
| 3fff | ram |     |     |      |      |
| 4000 |     |     |     |      |      |
| 5fff |     |     |     |      |      |
| 6000 |     |     |     | via1 |      |
| 6fff |     |     |     | via1 |      |
| 7000 |     |     |     |      | via2 |
| 7fff |     |     |     |      | via2 |
| 8000 |     | rom |     |      |      |
| ffff |     | rom |     |      |      |
#!/bin/python

# 0 = address should be 0 .. Duh
# 1 = address should be 1 .. Duh
# a = address 0 or 1
# x = not connected, future function

# try
#via1 = ["0","1","1","0","x","x","x","x","x","x","0","x","a","a","a","a"]

rom = ["1","a","a","a","a","a","a","a","a","a","a","a","a","a","a","a"]
ram = ["0","0","a","a","a","a","a","a","a","a","a","a","a","a","a","a"]
via1 = ["0","1","1","0","x","x","x","x","x","x","x","x","a","a","a","a"]
via2 = ["0","1","1","1","x","x","x","x","x","x","x","x","a","a","a","a"]
ps  = ["0","0","0","0","0","0","0","1","a","a","a","a","a","a","a","a"]

counter = 0
prevhexw = f"{0:04x}"

prevram = "nix"
prevrom = "nix"
prevps = "nix"
prevvia1 = "nix"
prevvia2 = "nix"

while counter < 65536:
    binw = f"{counter:016b}"
    hexw = f"{counter:04x}"
    binint = bin(int(counter))
    address=0

    ramcheck=0    
    romcheck=0    
    pscheck=0
    via1check=0
    via2check=0

    printram = "   "
    printrom = "   "
    printps = "   "
    printvia1 = "    "
    printvia2 = "    "
    myram=ram.copy()
    myrom=rom.copy()
    myps=ps.copy()
    myvia1=via1.copy()
    myvia2=via2.copy()
    while address < 16:

        if myram[address] == "a":
            myram[address]=binw[address]
        if myram[address] == "x":
            myram[address]=binw[address]
        if myram[address] != binw[address]:
            ramcheck=1

        if myrom[address] == "a":
            myrom[address]=binw[address]
        if myrom[address] == "x":
            myrom[address]=binw[address]
        if myrom[address] != binw[address]:
            romcheck=1

        if myps[address] == "a":
            myps[address]=binw[address]
        if myps[address] == "x":
            myps[address]=binw[address]
        if myps[address] != binw[address]:
            pscheck=1

        if myvia1[address] == "a":
            myvia1[address]=binw[address]
        if myvia1[address] == "x":
            myvia1[address]=binw[address]
        if myvia1[address] != binw[address]:
            via1check=1

        if myvia2[address] == "a":
            myvia2[address]=binw[address]
        if myvia2[address] == "x":
            myvia2[address]=binw[address]
        if myvia2[address] != binw[address]:
            via2check=1


        address=address+1

    if ramcheck==0:
        printram="ram"
    if romcheck==0:
        printrom="rom"
    if pscheck==0:
        printps="ps "
    if via1check==0:
        printvia1="via1"
    if via2check==0:
        printvia2="via2"


    if prevram != printram or prevrom != printrom or prevps != printps or prevvia1 != printvia1 or prevvia2 != printvia2:
        printlinep = f"| {prevhexw} | {prevram} | {prevrom} | {prevps} | {prevvia1} | {prevvia2} |"
        printline = f"| {hexw} | {printram} | {printrom} | {printps} | {printvia1} | {printvia2} |"
        if prevram != "nix":
            print(printlinep)
        print(printline)
    prevram=printram
    prevrom=printrom
    prevps=printps
    prevvia1=printvia1
    prevvia2=printvia2
    prevhexw=hexw
    counter=counter+1;
printline = f"| {hexw} | {printram} | {printrom} | {printps} | {printvia1} | {printvia2} |"
print(printline)

Badge picture plus sound in micropython

python mch2022-tools/webusb_fat_dir.py /flash/apps/python/easy
for f in easy.mp3 easy.png icon.png __init__.py ; do python  mch2022-tools/webusb_fat_push.py $f /flash/apps/python/easy/$f ; done

Micropython code __init__.py

mport display
import mch22
from audio import play
import buttons
from time import sleep
from machine import Pin
from neopixel import NeoPixel

powerPin = Pin(19, Pin.OUT)
dataPin = Pin(5, Pin.OUT)
np = NeoPixel(dataPin, 5)
powerPin.on()


def on_home_btn(pressed):
  if pressed:
    mch22.exit_python()


display.drawPng(0,0,"/apps/python/easy/easy.png")
display.flush()



# Led setup
#   2   3    
#      1
#     0     4

np[0] = (23,5,15)
np[1] = (3,15,22)
np[2] = (25,24,1)
np[3] = (25,24,1)
np[4] = (23,4,15)
np.write()


buttons.attach(buttons.BTN_HOME, on_home_btn)
# playing with volume 0 to wakeup sound device, else it is going to clip
play('/apps/python/easy/easy.mp3', volume=0)
sleep(7)
while True:
    play('/apps/python/easy/easy.mp3', volume=100)
    sleep(30)