You are here: Hello » blog

Pure python and very simple event management library

In event driven programming events are crucial. My requirements was Micropython platform on ESP32 micro-controller, so i could not use any other events library out-there. I've stumbled one very basic, very simple library and gave it a try… and it worked out-of-the-box for my case. When testing various event management libs out there I've stumbled on something similar, but it did not worked within classes. Python is nothing but classes everywhere :)

I was testing and extended this very simple python script, that perfectly works as main element in event driven development.

Strengths of library:

  • Observer can be declared before event type is created
  • Events can be fired even if there is no observers.
  • Works as pure python script
  • Works on micropython platform
  • Event name can be any string

I'm using this solution for event for timer, that fires each second and observe “ticker” where i need to update clock. I use clock in multiple places in my micropython script and i can get away with just one hardware timer used.

Honorable mentions goes to Pithikos from StackOverflow this answer

I have extended this library with possibility to forget event.

EventObserver.py
class Observer():
    _observers = []
 
    def __init__(self):
        self._observers.append(self)
        self._observed_events = []
 
    def observe(self, event_name, callback_fn):
        self._observed_events.append({'event_name': event_name, 'callback_fn': callback_fn})
 
    def forget(self, event_name):
        for dict_item in self._observed_events:
            for key, val in dict_item.items():
                if val == event_name:
                    self._observed_events.remove(dict_item)
 
 
class Event():
    def __init__(self, event_name, *callback_args):
        for observer in Observer._observers:
            for observable in observer._observed_events:
                if observable['event_name'] == event_name:
                    observable['callback_fn'](*callback_args)

Here is example of how to use this library

example.py
import EventObserver
 
# class object MUST inherit Observer object if you use it within class
class Room(Observer):
    def __init__(self):
        print("Room is ready.")
        Observer.__init__(self)  # DON'T FORGET THIS
        # observer can be declared already in class init method with following line
        # this.observe('someone sneezed', this.someone_sneezed)
 
    def someone_arrived(self, who):
        print(who + " has arrived!")
 
    def someone_sneezed(self, who):
        print(who + " has just sneezed!")
 
 
# Observe for specific event
room = Room()
room.observe('someone arrived', room.someone_arrived)
 
# Fire some events
Event('someone left', 'John')       # no events are attached to event "someone left" 
Event('someone arrived', 'Lenard')  # will output "Lenard has arrived!"
Event('someone sneezed', 'Jenny')   # will output "Jenny has just sneezed!"
 
# Remove known event
room.forget('someone arrived')
 
# no events based on 'someone arrived' will be fired
'''

RC Plane telemetry

I never forgot my old dream- to have my own DIY telemetry system

And here after like 7 years, when technology advanced (my knowledge, also)- I have finished building my project. And my main problems are solved with two unit of ESP32 microcontrolers and Android phone. Hardware is two ESP32 units with integrated SX1278 interface and one Beitian BN-220 GPS and GLONAS receiver.

I dont realy like C programming, so my choise of microcontroller was based on availability to use other languages for programming. Initial idea was to use Espruino firmware and use Javascript language for programming. But the issue at the time of research was BLE interface was not available (Harware supports it). Other options was Micropython and LUA. I have burned Micropython firmware into ESP32

So, here is how everything works: microcontroler ESP32 read GPS receiver data, extract required informaation and… taaadaaaa… =)

LoRa is used to transfer data to ground unit. Once i've tested range of my LoRa equiped ESP32's units- I've received over 2.2 km LOS at 433mhz. As i'm flying my plane in line of sight- it's plenty for me.

Ground unit listend for air unit frequincy, extract data and via BLE interfaace share this information with my Android device. Device application is created using Droidscript.

screenshot1.jpg screenshot2.jpg

Each time i'm testing something new, like programming language, i choose to build solution that would help in my life. This way I can learn more about tool, test is it suitable for me and solve my issue if I succeed.

Compile APK online

It was long time i was dreaming about ability to compile apk online. So this blog post (tutorial) will be how to prepare C9 or Goorm online IDE or any similar based on ubuntu linux to be able to develop online.

First of all, create new empty ubuntu box and resize it to 1Gb RAM and 5GB storage. Simple APK compile stull will require about 1GB of storage, but if you decide to go on gradle dependency management system- storage will grow to 2.5GB.

I prepending everyhing with sudo command, in case any permission will be missing.

Prepare your system

So lets begin from very basic. At first you need JAVA, so add OpenJDK repository and install java

sudo add-apt-repository ppa:openjdk-r/ppa
sudo apt-get update

Install Java headless, because you do not need GUI here

sudo apt-get install openjdk-8-jdk-headless

Download SDK zip from android home. You may use my provided link

wget https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip

Make directory for android SDK and extract ZIP

sudo mkdir -p /opt/android-sdk
sudo unzip sdk-tools-linux-4333796.zip -d /opt/android-sdk

Now add environment variables to your system.

sudo nano /etc/profile

and at the very end add following lines

Always check if copying from website does not ruin you double-quotes

export ANDROID_HOME="/opt/android-sdk"
export JAVA_HOME="/usr/lib/jvm/java-1.8.0-openjdk-amd64"
export PATH=$JAVA_HOME/bin:$ANDROID_HOME/tools/:$ANDROID_HOME/platform-tools/:$PATH

Save and exit by pressing CTRL+X on keyboard and confirming that you want to save changes by Y. Restart your machine or environment.

Now you need to add SDK, Tools and platform stuff. I have chosen 24 version so i have used this command

sudo /opt/android-sdk/tools/bin/sdkmanager "tools" "platforms;android-24" "build-tools;24.0.3"

in case you want something else or want to see available list use sdkmanager –list command

Looks like everything is prepared, now need “Hello world!” android application. You may need to prepare it according structure and create all files or You can download this HelloAndroid project and extract in in your workspace.

Steps needs to be done to get APK file

  1. Generate R.java file AAPT
  2. Compile java file with javac
  3. Translate it to Dalvik Bytecode with DX
  4. Make apk with AAPT
  5. Align apk package with ZIPALIGN
  6. Sign your apk file with APKSIGNER

AS you can see, there is a step to sign you apk install file with certificate. You can create your own. In main project directory, the same where AndroidManifest.xml file exist, run following command to create private key:

keytool -genkeypair -validity 365 -keystore mykey.keystore -keyalg RSA -keysize 2048

Answer all questions and provide password.

Thats it. Now you can create APK file from command line. To create automated, here is prepared bash script witch you should save in project root directory (the same as android manifest) and run to build your project. I have chosen to name it make.sh

make.sh
#!/bin/bash
 
set -e
 
AAPT="/opt/android-sdk/build-tools/24.0.3/aapt"
DX="/opt/android-sdk/build-tools/24.0.3/dx"
ZIPALIGN="/opt/android-sdk/build-tools/24.0.3/zipalign"
APKSIGNER="/opt/android-sdk/build-tools/24.0.3/apksigner"
PLATFORM="/opt/android-sdk/platforms/android-24/android.jar"
 
echo "Cleaning..."
rm -rf obj/*
rm -rf src/in/ignas/helloandroid/R.java
rm -rf bin/*
 
echo "Generating R.java file..."
$AAPT package -f -m -J src -M AndroidManifest.xml -S res -I $PLATFORM
 
echo "Compiling..."
javac -d obj -classpath src -bootclasspath $PLATFORM -source 1.7 -target 1.7 src/in/ignas/helloandroid/MainActivity.java
javac -d obj -classpath src -bootclasspath $PLATFORM -source 1.7 -target 1.7 src/in/ignas/helloandroid/R.java
 
echo "Translating in Dalvik bytecode..."
$DX --dex --output=classes.dex obj
 
echo "Making APK..."
$AAPT package -f -m -F bin/hello.unaligned.apk -M AndroidManifest.xml -S res -I $PLATFORM
$AAPT add bin/hello.unaligned.apk classes.dex
 
echo "Aligning and signing APK..."
$ZIPALIGN -f 4 bin/hello.unaligned.apk bin/hello.apk
$APKSIGNER sign --ks mykey.keystore bin/hello.apk

In case you have used different versions in sdkmanager command- edit path in header accordingly. Just run this script with following command. If you can not run it chmod +x make.sh

./make.sh

Script will ask password for your keystore that you provided earlier.

This solution works if your application does not have any dependencies on external libs and gradle wrapper is not used. Probably, automated install script can be made but that's for another times. In case you have any suggestions, comment or anything worth to say- comment below.

Pyle PSWWM82BK review

Hello my readers. This record will be quite different from previous, as I'll try to write review for a watch.

For quite long time I wanted hi-tech type watch. For now, technologically advanced watches is Altimeter-Barometer-Compass (ABC) watches. Also, there is wrist computers (ABC, GPS, etc) but it's not intended for everyday regular use, so I did not even considered this type of watches. I've searched for ABC watch and preselected few model: Casio Casio PRG-500, Pyle PSWWM82BK, Weather master 7. Casio was little bit to expensive for me, WM7 was bulky in view. So I've chosen Pyle. Probably it's just rebranded no-name but I liked inverted LCD, nice outfit and reasonable price.

Now let's get it to the topic, where we should be.

Unboxing

Received quite nice looking hard-paper box with transparent window to watch itself.

Manual

Manual, included with this watch is written in english and french languages. It was really good written, understandable and with nice and explainable illustrations. Everything is detailed in sections. High mark for manual!

Settings up the watch

After taking watch into hands it was disabled. As understood later- it was in sleep. Just press any button and it comes to life. Great! After reading manual I've managed to set time correctly. Also set altitude above level based on GPS measurements. 30 mins. it's all what it takes to understand what is what. After that I've put manual back to box as my watch was ready for everyday use

Features

Every watch primary function is to tell it's wearer what time is it now. This clock show it in big digits on main screen. Above clock line you may see day of the week, bellow- date. Time and Date formats can be chosen, 12/24 hours and MM-DD or DD-MM as date. Year in not visible all the time. But why would you like to see current year? Watch as apparatus to tell time is perfect.

But hey, it also has some other great features: Chronograph up to 99 hours with 10 laps history, Count-Down timer from 99 hours, second time zone if you travel frequently or have any other needs to track time in different timezone. It has two different alarms and may chime hourly. This watch has thermometer- and it's accurate. But you have to take it off from hand to read surrounding temperature. Temp will be ready in about 10 minutes

Pyle PSWWM82 may read weather pressure and show it in different formats (mBar, hPa, InHg). It remembers hourly reading for 36 hours and may predict forthcoming weather by showing one of 4 icons: Sunny, Sun in clouds, Cloudy and Raining. Based on pressure reading this watch may calculate difference in altitude (with exception that weather not changing drastically). This instrument is accurate: at home I've set ground zero, got to work and in evening came back. At home it shown -1 meter. This misread was because air pressure is constantly changing. It shows min or max altitude, and total ascend and descend.

And one more great feature- compass. Nothing to much about it. Just need to calibrate it at beginning and set magnetic declination based on your location. If clock is not in horizontal position- upper line blinks to show it. Also it blinks if magnetic disturbance is detected- strong magnetic or electric field are detected. Compass works very well, easy to read and use. Oh, almost forgot- this gadget has EL panel as back-light. With EL Panel all face is light equally and easy to read in darkness. Not to bright if you just woke up at night and want to check time- it wont flash with light in your eyes.

Usability

Inverted LCD (when everything is black and digits are white) looks nice, easy to read in bright light or at home. But when it comes to quality of watch as item, I'm not so enthusiastic. Front face glass (crystal as other calls it) is probably mineral- in other words- glass. That's why care should be taken to preserve crystal from scratches. I've applied screen protector while this watch isn't scratched badly. Probably, some day I'll have to replace crystal, but as far as my quick research says- it not very trivial task. Front crystal size is 33mm- and it's quite usable format in nowadays- so your watch service technician should be able to do the job.

Plastic of band is quite hard (not even close to rubber or silicon) but I like it.

Conclusion

I've wrote this part after one month of usage

  • Looks sportish
  • Easy to see digits in bright sunlight and in artificial lightning.
  • Night light is not to bright or to dark
  • Accurate measurement and forecast
  • Armband and clock is quite durable
  • No noticeable time drift

I'm happy with my gadget :)

2017/07/21 13:18 · 0 Comments

Reliable way to get date in batch scripting

It's been long time since my last post, but I'm here, and watching :-)

Lately, I've got assignment to create MySQL backup script. It must be automatically scheduled by MS Windows Task Scheduler. As it is automatic, script should create new backup name each time. What is the best way to name backups? Probably to include date of backup.
And here my problems begins. If you grab date file_%date%.bak you may end up in various ways:

  • File can be created and named as you've expected;
  • Back up file does not appear (because of illegal characters used as date separator);
  • Backup file named somehow strangely.

I've tried all various ways to create file names as I wanted to by splitting date into Year, Mont and Day. But when it comes to locale- date can be in imperial style: YYYY/DD/MM
I want universal script to work on all locales or formats, so tried to catch date separator to guess format. This kind of tinkering complicated my script till unusable… And suddenly I step over WMI1) once again. This instrument is life saver. For real!! I have found Win32_OperatingSystem class in root\CIMV2 namespace. And you know what? It has exactly what I need. I just needed to query LocalDateTime property to get Date and time. This property hold my valuables in this format:

YearMonthDayHourMinuteSecond.Microsecond+Timezone
20130625094846.381000+180

This format is independent from locale or whatever else factors, it's allways the same.
Now I see my road bright and clear- I must use WMI to get my date and split it into Year, Mont and Day. This could be done quite simply in batch scripting file:

@ECHO OFF
for /f %%a in ('wmic os get LocalDateTime ^| findstr ^[0-9]') do (set ts=%%a)
ECHO %ts:~0,8%-%ts:~8,4%

This way I get 20130625-0948

So just script your filename as following and you are ready to go

SET filename = %ts:~0,8%.bak
2014/02/04 20:18 · 1 Comment

Older entries >>

1) Windows Management Instrument
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported

Hey.lt - Nemokamas lankytojų skaitliukas XHTML