Monitor Temperatures using Bluetooth Xiaomi Mijia Thermostat MJ_HT_V1 Linux (Python & Bash)

With Bash:

1. Create checktemp.sh:
#!/bin/bash
RES=$(timeout 30 gatttool --device=AA:AA:AA:AA:AA:AA --char-write-req -a 0x0010 -n 0100 --listen)
echo $RES

2. Run it:
chmod +x checktemp.sh
./checktemp.sh

With Python:

1. Download script: https://github.com/pFenners/mijia-sensor-domoticz/blob/master/mijia/mijia_poller.py

2. Download script: https://github.com/pFenners/mijia-sensor-domoticz/blob/master/domoticz_mijia.py

3. Comment out script:
domoticzrequest("http://" + domoticzserver ...
to
# domoticzrequest("http://" + domoticzserver ...

4. Change with your device mac:
update("AA:AA:AA:AA:AA:AA","1")

5. Run:
python3 domoticz_mijia.py

Another info:
#dev name
for c in $(gatttool --device=AA:AA:AA:AA:AA:AA --char-read -a 0x0003 | cut -c 34-); do echo '0x'$c|xxd -r; done
#battery
printf "%d\n" "0x"$(gatttool --device=AA:AA:AA:AA:AA:AA --char-read -a 0x0018 | cut -c 34-)
#manufacturer
for c in $(gatttool --device=AA:AA:AA:AA:AA:AA --char-read -a 0x001c | cut -c 34-); do echo '0x'$c|xxd -r; done
#model
for c in $(gatttool --device=AA:AA:AA:AA:AA:AA --char-read -a 0x001e | cut -c 34-); do echo '0x'$c|xxd -r; done
#sn
gatttool --device=AA:AA:AA:AA:AA:AA --char-read -a 0x0020 | cut -c 34-
#hw rev
for c in $(gatttool --device=AA:AA:AA:AA:AA:AA --char-read -a 0x0022 | cut -c 34-); do echo '0x'$c|xxd -r; done
#sw rev
for c in $(gatttool --device=AA:AA:AA:AA:AA:AA --char-read -a 0x0024 | cut -c 34-); do echo '0x'$c|xxd -r; done

Monitor Temperatures using Bluetooth Xiaomi Mijia Thermostat MJ_HT_V1 C# Script

1. install windows 10 sdk (we need this file “\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.17763.0\Windows.winmd”)
https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk/

2. get the scripts
a. utilities
https://github.com/Andy9FromSpace/ble-scripts/tree/master/Utilities
b. mijia bluetooth
https://github.com/Andy9FromSpace/ble-scripts/tree/master/MJ-HT-V1

3. download and install c# script runner (you need one of these):
a. dude (don’t need visual studio)
https://github.com/adamralph-archive/dude
b. visual studio (includes csi.exe)
https://www.visualstudio.com/vs/community/

4. discover your device
dude DeviceEnumerate.csx

5. connect and see results
a. sensor data
rem device manager – association endpoint id
rem BluetoothLE#BluetoothLE18:5e:xx:xx:xx:xx-4c:65:xx:xx:xx:xx
..\dude MJHTV1GetSensorData.csx –device-id=BluetoothLE#BluetoothLE00:1a:xx:xx:xx:xx-4c:65:xx:xx:xx:xx
pause
b. device status (battery info)
rem device manager – association endpoint id
rem BluetoothLE#BluetoothLE18:5e:xx:xx:xx:xx-4c:65:xx:xx:xx:xx
..\dude MJHTV1GetStatus.csx –device-id=BluetoothLE#BluetoothLE00:1a:xx:xx:xx:xx-4c:65:xx:xx:xx:xx
pause

Two Way Audio with XiaoFang Hack

XiaoFang IP Camera with samtap’s fang-hacks (https://github.com/samtap/fang-hacks), you can get 2-way audio with a little trick:

1. download necessary files (from https://github.com/samtap/fang-hacks/issues/305) and put it on /media/mmcblk0p2/snx_audio (dont forget to set permission execute):
- snx_audio_playback
- snx_audio_record

2. remote speaker:
# set gpio
gpio_ms1 -n 7 -m 1 -v 1
# listen audio data in port 11032 on camera
tcpsvd 0.0.0.0 11032 /media/mmcblk0p2/snx_audio/snx_audio_playback -d s16 -s 32k -f -
# stream audio from pc to camera
ffmpeg.exe -i input -ar 16k -f s16le tcp://your-cam-ip:11032

2b. alternative one-line:
ffmpeg.exe -i input -ar 16k -f s16le - | ssh root@your-cam-ip /media/mmcblk0p2/snx_audio/snx_audio_playback -d s16 -s 32k -f -

3. remote mic (disable snx_rtsp_server audio first at /media/mmcblk0p2/data/etc/scripts/20-rtsp-server):
# listen port 12016, ready to stream audio data
tcpsvd 0.0.0.0 12016 /media/mmcblk0p2/snx_audio/snx_audio_record -d s16 -s 16k -f -
# play on pc
ffplay -f s16le -ar 16k -ac 1 -nodisp tcp://your-cam-ip:12016

3b. alternative one-line:
ssh root@your-cam-ip /media/mmcblk0p2/snx_audio/snx_audio_record -d s16 -s 16k -f - | ffplay -f s16le -ar 16k -ac 1 -nodisp -

4. Enable SSH key login (the /root home directory isn’t writable so we have to move it):
cp -r /root /media/mmcblk0p2/
sed -i 's#/root#/media/mmcblk0p2/root#g' /etc/passwd
mkdir -p /media/mmcblk0p2/root/.ssh
chmod 700 /media/mmcblk0p2/root/.ssh
touch /media/mmcblk0p2/root/.ssh/authorized_keys
chmod 600 /media/mmcblk0p2/root/.ssh/authorized_keys
echo 'YOUR_KEY_HERE' >> /media/mmcblk0p2/root/.ssh/authorized_keys

Source:
– https://github.com/samtap/fang-hacks/blob/ca435dd90e1bf290d58d31874be594af34cf21a5/INSTALL.md
– https://github.com/samtap/fang-hacks/issues/305
– https://github.com/samtap/fang-hacks/issues/310
– https://github.com/EliasKotlyar/Xiaomi-Dafang-Hacks/issues/718

Zoneminder Alarm Custom Logging (& Notification)

Zoneminder already provide alarm notification by email, but you can’t send the image in it’s email notification (yes, you can see tags below). Instead, you can use custom script to send notification via messaging such as telegram

1. create new filter, put this in its fields:
– Alarm Frames >= 10
– (and) Start Date/Time >= -1 hour
– (and) Monitor Id = 1
– Message details of all matches: checked (you need to set OPT_MESSAGE in email options) otherwise you’ll only get notification after an event finished, not immediately
– Execute command on all matches:
/home/zmuser/logalarm.sh "%EI%" "%EN%" "%ET%" "%EL%" "%EFA%" "%EST%" "%ESA%" "%EP%" "%EFMOD%" "%EPI%" "%EPI1%" "%MN%" "%MP%"
– Run filter in background: checked
* For other tags you can use see below

2. create file logalarm.sh (this script only do logging, you can change this script to do notification via telegram using telegram-cli https://github.com/vysheng/tg):
#!/bin/sh
LOGF=/home/zmuser/alarm.log
echo "--- $(date '+%F %T')" >> ${LOGF}
echo "$1" >> ${LOGF}
echo "$2" >> ${LOGF}
echo "$3" >> ${LOGF}
echo "$4" >> ${LOGF}
echo "$5" >> ${LOGF}
echo "$6" >> ${LOGF}
echo "$7" >> ${LOGF}
echo "$8" >> ${LOGF}
echo "$9" >> ${LOGF}
echo "$10" >> ${LOGF}
echo "$11" >> ${LOGF}
echo "$12" >> ${LOGF}
echo "$13" >> ${LOGF}
echo "$14" >> ${LOGF}
echo "LOGGED OK"
exit 0

3. create alarm.log and make sure it’s accessible:
touch /home/zmuser/alarm.log
chmod 666 /home/zmuser/alarm.log

Here is tags you can use in the field:
%EI% Id of the event - eg 703507
%EN% Name of the event - eg Event- 703507
%EC% Cause of the event
%ED% Event description
%ET% Time of the event - eg 2020-04-15 12:10:00
%EL% Length of the event - eg 600.00
%EF% Number of frames in the event - eg 600
%EFA% Number of alarm frames in the event - eg 618
%EST% Total score of the event - eg 2597
%ESA% Average score of the event - eg 4
%ESM% Maximum score of the event - eg 69
%EP% Path to the event - eg ?view=event&mid=2&eid=703507
%EFMOD% Path to image containing object detection, in frame view (need 3rd party object detection event server)
%EIMOD% Path to image containing object detection, in frame view (need 3rd party object detection event server)
%EPS% Path to the event stream
%EPI% Path to the event images - eg ?view=event&mode=still&mid=2&eid=703507
%EPI1% Path to the first alarmed event image - eg ?view=frame&mid=2&eid=703507&fid=3326
%EPIM% Path to the (first) event image with the highest score
%MN% Name of the monitor - eg 12_LV2_BRH
%MET% Total number of events for the monitor
%MEH% Number of events for the monitor in the last hour
%MED% Number of events for the monitor in the last day
%MEW% Number of events for the monitor in the last week
%MEM% Number of events for the monitor in the last month
%MEA% Number of archived events for the monitor
%MP% Path to the monitor window - eg ?view=watch&mid=2
%MPS% Path to the monitor stream
%MPI% Path to the monitor recent image
%FN% Name of the current filter that matched
%FP% Path to the current filter that matched
%ZP% Path to your ZoneMinder console
LAST_PARAM path to the event folder - eg /var/cache/zoneminder/events/2/2020-04-15/703507

Below are tags for email only (can’t use with execute):
%EI1% Attach first alarmed event image
%EI1A% Attach first alarmed event image (analyse)
%EIM% Attach (first) event image with the highest score
%EIMA% Attach (fist) event image with the highest score (analyse)
%EV% Attach event mpeg video
%EVM% Attach event 3gp video for mobile

Source:
– https://github.com/vysheng/tg
– https://forums.zoneminder.com/viewtopic.php?t=22053

Remote Lubuntu (VNC and SSH server)

Lubuntu not installed ssh and vnc server, so you can install it yourself

1. Install required packages:
sudo apt install openssh-server vino
sudo reboot

2. At this point you should be able to connect via ssh, but vnc not working yet, unfortunately vino no longer ship with vino-preferences, there is no easy way to configure it (bug list https://bugs.launchpad.net/ubuntu/+source/vino/+bug/1775999):
# list settings
gsettings list-keys org.gnome.Vino
# disable prompt
gsettings set org.gnome.Vino prompt-enabled false
# set auth method
gsettings set org.gnome.Vino authentication-methods "['vnc']"
# set password
gsettings set org.gnome.Vino vnc-password $(echo -n "password"|base64)
# disable encryption
gsettings set org.gnome.Vino require-encryption false

3. Start the vnc server:
DISPLAY=:0 /usr/lib/vino/vino-server

4. Setting autostart:
~/.config/autostart/vino-server.desktop
[Desktop Entry]
Type=Application
Name=Vino VNC server
Exec=/usr/lib/vino/vino-server
NoDisplay=true

mkdir ~/.config/autostart
nano ~/.config/autostart/systemctl.desktop

[Desktop Entry]
Type=Application
Exec=systemctl --user start vino-server
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name=Vino Server
Comment=Auto-start the VNC service on login in

4b. Xubuntu autostart

sudo cp /usr/share/applications/vino-server.desktop /etc/xdg/autostart/vino-server.desktop

Source:
– https://askubuntu.com/questions/4474/enable-remote-vnc-from-the-commandline
– https://wiki.archlinux.org/index.php/Vino
– https://askubuntu.com/questions/1062727/how-to-get-vino-vnc-server-to-start-on-startup-in-ubuntu-18-04-1

Octroprint: Turn off webcam automatically

Seen a post about webcam at jcode, i made my own version because:
1. need no additional python libraries
2. need camera stay on while printer is on, ready for next print, not depending on octoprint status

Running cron script every minute:

* * * * * /home/pi/autocam.py

and script autocam.py:

#!/usr/bin/python

import os
import subprocess

SERIAL_DEV = "/dev/serial/by-id/your-serial-port-id"

def checkserial():
  return os.path.exists(SERIAL_DEV)

def checkwebcam():
  r = subprocess.check_output("ps ax | grep mjpg_streamer -c",shell=True)
  c = int(r)-2
  return c > 0

if __name__ == "__main__":
  if checkserial() and not checkwebcam():
    os.system("echo $(date '+%Y-%m-%d %H:%M:%S') start >> autocam.log")
    os.system("service webcamd start")
  elif not checkserial() and checkwebcam():
    os.system("echo $(date '+%Y-%m-%d %H:%M:%S') stop >> autocam.log")
    os.system("service webcamd stop")

Source: https://jcode.me/octoprint-turning-off-webcam-automatically/

Raspbian Shutdown from web

sudo apt-get update && sudo apt-get install lighttpd php-cgi
sudo lighty-enable-mod fastcgi fastcgi-php
sudo service lighttpd force-reload
sudo visudo
# Add the following line below “pi ALL etc.” and exit the visudo editor:
www-data ALL = NOPASSWD: /sbin/shutdown
sudo nano /var/www/index.html

<html><a href="shutdown.php">Shutdown NOW</a></html>

sudo nano /var/www/shutdown.php

<?php system('sudo /sbin/shutdown -h now'); ?>

Source: https://www.raspberrypi.org/forums/viewtopic.php?t=58802

Toggle Matchbox Keyboard

I added a “launchbar” icon in the taskbar, to act as a toggle switch, so touching the icon started matchbox and touching it again closed matchbox. That seems to be what you’re looking for.

Looking at my notes this is what I did, and it should still work since matchbox-keyboard hasn’t been updated in a long time.

All the keyboard layouts provided in the install are located at /usr/share/matchbox-keyboard. You’ll see a list of .xml files, choose the one closest to what you need, the file names are somewhat descriptive. The .xml file you choose can also be edited to customize the characters, spacing, size, key location, etc. for the keyboard. If you copy that file of choice to your home directory that is the keyboard file it will use, you won’t have to specify a layout when starting matchbox-keyboard, and you can edit that user file and leave the original .xml files unchanged in case you need to back up or start over.

First create a .matchbox directory

mkdir ~/.matchbox

Then copy your .xml file of choice to that directory, in this example I used the US keyboard

cp /usr/share/matchbox-keyboard/keyboard-us.xml ~/.matchbox/keyboard.xml

After that all your .xml keyboard edits will be done in ~/.matchbox/keyboard.xml

nano ~/.matchbox/keyboard.xml

Now that you have a default keyboard file in place to make startup and editing easier you’ll need to create a bash script that will either toggle the keyboard on or off each time the script is run. I use a “scripts” directory to hold all my bash scripts, but you can put it wherever you like.

nano ~/toggle-matchbox.sh

#!/bin/bash
#This script toggles the virtual keyboard on or off
PID=`pidof matchbox-keyboard`
if [ ! -e $PID ]; then
killall matchbox-keyboard
else
matchbox-keyboard &
fi

Don’t forget to make it executable.

Now you’ll need to create a desktop file, this will add it to the menu, and allow you to add it to the launchbar so you can start/stop the keyboard with a single touch of the icon in the taskbar. Edit the path to your “toggle” shell script as needed.

sudo nano /usr/share/raspi-ui-overrides/applications/toggle-matchbox.desktop

[Desktop Entry]
Name=Toggle Matchbox Keyboard
Comment=Toggle Matchbox Keyboard
Exec=/home/pi/toggle-matchbox.sh
Type=Application
Icon=matchbox-keyboard.png
Categories=Panel;Utility;MB
X-MB-INPUT-MECHANSIM=True

Now you need to add it to the “Launchbar” for a one touch start/stop. You can use the Desktop GUI to add a button to the launchbar, but sometimes the Pi doesn’t update the menu in a timely manner after you’ve made changes, and you can’t add it to the launchbar until it shows up in the menu if you’re using the GUI. So I just went ahead and added the “toggle matchbox” button manually.

I did that by adding an entry to the launchbar plugin, so open the lxpanel file for editing

nano ~/.config/lxpanel-pi/LXDE/panels/panel

Scroll down the file till you see the section for the launchbar plugin. You can see I currently have 4 buttons in the launchbar

Plugin {
type=launchbar
Config {
Button {
id=/usr/share/raspi-ui-overrides/applications/pcmanfm.desktop
}
Button {
id=/usr/share/raspi-ui-overrides/applications/lxterminal.desktop
}
Button {
id=/usr/share/applications/iceweasel.desktop
}
Button {
id=/usr/share/raspi-ui-overrides/applications/galculator.desktop
}
}
}

Add the new button entry to the launchbar plugin. I added mine to the top of the “button” list so it would show up next to the “Menu” button. If you want the toggle button to appear to the right add it at the bottom of the list, or even somewhere in the middle of the list.
This is what the file looked like after adding the button.

Plugin {
type=launchbar
Config {
Button {
id=/usr/share/raspi-ui-overrides/applications/toggle-matchbox.desktop
}
Button {
id=/usr/share/raspi-ui-overrides/applications/pcmanfm.desktop
}
Button {
id=/usr/share/raspi-ui-overrides/applications/lxterminal.desktop
}
Button {
id=/usr/share/applications/iceweasel.desktop
}
Button {
id=/usr/share/raspi-ui-overrides/applications/galculator.desktop
}
}
}

Now restart lxpanel and you should see the new “button” in the launchbar. Touch it to open the keyboard, touch it again to close.

lxpanelctl restart

As I said in the beginning I’m using notes and my memory for this since I’m not currently using matchbox-keyboard. But everything appears to be correct, and I usually keep good notes when adding things, so it should work fine. Maybe it will help you out in finding a solution.

Source: https://www.raspberrypi.org/forums/viewtopic.php?t=112515

Calibrate Waveshare 5″ Resistive Touchscreen (and 7.9″ Capacitive)

config.txt
max_usb_current=1
hdmi_group=2
hdmi_mode=87
hdmi_cvt 800 480 60 6 0 0 0
hdmi_drive=1

# install calibrator and evdev (allows multiple keyboards mice treated as separate device)
sudo apt install xinput-calibrator xserver-xorg-input-evdev

# make evdev higher number than libinput
sudo mv /usr/share/X11/xorg.conf.d/10-evdev.conf /usr/share/X11/xorg.conf.d/45-evdev.conf

# list devices
xinput

# view calibration option
xinput --list-props <deviceid>

# calibrate
xinput_calibrator

# copy paste the result like below to /usr/share/X11/xorg.conf.d/99-calibration.conf:
Section "InputClass"
Identifier "calibration"
MatchProduct "BYZHYYZHY By ZH851"
Option "Calibration" "182 3859 277 3944"
Option "SwapAxes" "0"
EndSection

# checkĀ  the values
DISPLAY=:0 xinput list-props "BYZHYYZHY By ZH851"

# manual set values
DISPLAY=:0 xinput set-prop "BYZHYYZHY By ZH851" "Evdev Axis Calibration" 200, 3800, 275, 3850

ALTERNATIVE (using libinput):
# check calibration values
xinput_calibrator -v
DEBUG: Found that 'BYZHYYZHY By ZH851' is a sysfs name.
DEBUG: Adding click 0 (X=129, Y=86)
DEBUG: Adding click 1 (X=655, Y=96)
DEBUG: Adding click 2 (X=133, Y=406)
DEBUG: Adding click 3 (X=669, Y=401)

# check screen resolution
xrandr | grep current
Screen 0: minimum 800 x 480, current 800 x 480, maximum 800 x 480

# calculate values
a = (screen_width * 6 / 8) / (click_3_X - click_0_X)
c = ((screen_width / 8) - (a * click_0_X)) / screen_width
e = (screen_height * 6 / 8) / (click_3_Y - click_0_Y)
f = ((screen_height / 8) - (e * click_0_Y)) / screen_height

a = (800 * 6 / 8) / (669 - 129) = 1.1111
c = ((800 / 8) - (1.1111 * 129)) / 800 = -0.0542
e = (480 * 6 / 8) / (401 - 86) = 1.1429
f = ((480 / 8) - (1.1429 * 86)) / 480 = -0.0798

# test new values
xinput set-prop "BYZHYYZHY By ZH851" "libinput Calibration Matrix" a, 0.0, c, 0.0, e, f, 0.0, 0.0, 1.0

xinput set-prop "BYZHYYZHY By ZH851" "libinput Calibration Matrix" 1.1111, 0.0, -0.0542, 0.0, 1.1429, -0.0798, 0.0, 0.0, 1.0

# if calculation incorrect, reset and repeat calculation above
xinput set-prop "BYZHYYZHY By ZH851" "libinput Calibration Matrix" 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0

# make changes permanent to /usr/share/X11/xorg.conf.d/99-calibration.conf:
Section "InputClass"
Identifier "calibration"
MatchProduct "BYZHYYZHY By ZH851"
Option "TransformationMatrix" "1.1111 0.0 -0.0542 0.0 1.1429 -0.0798 0.0 0.0 1.0"
EndSection

For 7.9″ Capacitive Screen:

add this lines to /boot/config.txt:
#disable these settings below
#display_auto_detect=1
#dtoverlay=vc4-kms-v3d
#max_framebuffers=2
max_usb_current=1

hdmi_group=2
hdmi_mode=87
hdmi_timings=400 0 100 10 140 1280 10 20 20 2 0 0 0 60 0 43000000 3
display_rotate=3 # 1 - 90deg, 2 - 180deg, 3 - 270deg

Rotate 0 degree:
xinput set-prop "WaveShare WaveShare" "libinput Calibration Matrix" 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0

Rotate 90 degree:
xinput set-prop "WaveShare WaveShare" "libinput Calibration Matrix" 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, 0.0, 1.0

Rotate 270 degree:
xinput set-prop "WaveShare WaveShare" "libinput Calibration Matrix" 0.0, -1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0

# make changes permanent to /usr/share/X11/xorg.conf.d/99-calibration.conf:
Section "InputClass"
Identifier "calibration"
MatchProduct "WaveShare WaveShare"
Option "TransformationMatrix" "0.0 -1.0 1.0 1.0 0.0 0.0 0.0 0.0 1.0"
EndSection

Source:
https://www.waveshare.com/wiki/5inch_HDMI_LCD_(B)
https://www.waveshare.com/wiki/7.9inch_HDMI_LCD
https://wiki.archlinux.org/index.php/Talk:Calibrating_Touchscreen