Xiaomi Miflora Sensor Integration

Hi. This thread is slowly becoming big, and complex with many solutions. Could anyone clean it up and make a step by step guide? Also is there a binding or something in the works to make it easier? Id like to get it to work with a rpi 1 but its kinda complex reading bits of a forum. Thanks!

I’m having a lot of stuff at work and at home (moving to a new house), won’t be able to support any of this until the middle of march.

/S

Thanks for your reply even you are in such busy status,
except the auto generate items part,
everything works like a charm,
Thanks for your hardwork and have a nice day~

I think this little toy works good with MQTT,
just sometimes revert data will have mess data,like below,

connect: Device or resource busy (16)
connect: Device or resource busy (16)
connect: Device or resource busy (16)
connect: Device or resource busy (16)
Temperature: 4804.2
Moisture: 136
Light: 61149
Conductivity: 26231
Battery: 100

I use @Seaside 's code and add some filter, as I am don’t really know how to coding, I just modify a little

I modify the code from line 25

 if (( $(echo "$TEMP0 < 80" |bc -l ) )); then
  mosquitto_pub -h $MOSQ_SERVER -m $TEMP0 -t plants/"${plant_name,,}"/temp -q 1
  fi
  if [ "$MOIST0" -lt 80 ]; then
  mosquitto_pub -h $MOSQ_SERVER -m $MOIST0 -t plants/"${plant_name,,}"/moist -q 1
  fi  
  if [ "$LIGHT0" -lt 10000 ]; then
  mosquitto_pub -h $MOSQ_SERVER -m $LIGHT0 -t plants/"${plant_name,,}"/light -q 1
  fi
  if [ "$COND0" -lt 500 ]; then
  mosquitto_pub -h $MOSQ_SERVER -m $COND0 -t plants/"${plant_name,,}"/cond -q 1
  fi
  if [ "$BATTERY0" -lt 101 ]; then
  mosquitto_pub -h $MOSQ_SERVER -m $BATTERY0 -t plants/"${plant_name,,}"/battery -q 1
  fi

so bash won’t post incorrect data to openhab for storage.
below are original code, so basicly by pass the middle command
run sproute.sh -l at first time,
than set time schedule by crontab -e
add */45 * * * * /home/pi/sproute/sproute2.sh -p
which mean update every 45 mins

#!/bin/bash -

#sproute.sh -l   - Will list all mac-addresses with Mi Flower
#sproute.sh -o   - Will generate Openhab items calling java program
#sproute.sh -p   - Will poll and publish data using mqtt

MOSQ_SERVER="10.1.1.1"
CHECK_PLANT="/home/pi/miflora/checkplant.py"
SCAN_RESULT_FILE="/tmp/result.txt"
PLANT_ITEMS_FILE="/home/pi/plants.items"
SPROUTE_JAR="/home/pi/sproute/sproute.jar"
SPROUTE_PROPS="/home/pi/sproute.properties"
PLANT_FILES_DIR="/home/pi/plants"

plantCheck() {
  LOGROW=`python3 $CHECK_PLANT "${plant_mac}"`
  echo $LOGROW >> "/var/log/plant.${plant_log_suffix}.log"

  TEMP0=`echo $LOGROW | awk '{print $4}'`
  MOIST0=`echo $LOGROW | awk '{print $6}'`
  LIGHT0=`echo $LOGROW | awk '{print $8}'`
  COND0=`echo $LOGROW | awk '{print $10}'`
  BATTERY0=`echo $LOGROW | awk '{print $12}'`

  mosquitto_pub -h $MOSQ_SERVER -m $TEMP0 -t plants/"${plant_name,,}"/temp -q 1
  mosquitto_pub -h $MOSQ_SERVER -m $MOIST0 -t plants/"${plant_name,,}"/moist -q 1
  mosquitto_pub -h $MOSQ_SERVER -m $LIGHT0 -t plants/"${plant_name,,}"/light -q 1
  mosquitto_pub -h $MOSQ_SERVER -m $COND0 -t plants/"${plant_name,,}"/cond -q 1
  mosquitto_pub -h $MOSQ_SERVER -m $BATTERY0 -t plants/"${plant_name,,}"/battery -q 1

  mosquitto_pub -h $MOSQ_SERVER -m ${plant_moist_low} -t plants/"${plant_name,,}"/moistlow -q 1
  mosquitto_pub -h $MOSQ_SERVER -m ${plant_moist_high} -t plants/"${plant_name,,}"/moisthigh -q 1

  mosquitto_pub -h $MOSQ_SERVER -m ${plant_conductivity_low} -t plants/"${plant_name,,}"/condlow -q 1
  mosquitto_pub -h $MOSQ_SERVER -m ${plant_conductivity_high} -t plants/"${plant_name,,}"/condhigh -q 1

  echo "Published ${plant_log_suffix}: TEMP=$TEMP0 MOIST=$MOIST0 LIGHT=$LIGHT0 COND=$COND0 BATTERY=$BATTERY0"
  echo "Published COND_LOW=${plant_conductivity_low} COND_HIGH=${plant_conductivity_high}"

  sleep 10
  MILLIS=`date +%s%N | cut -b1-13`
  mosquitto_pub -h $MOSQ_SERVER -m $MILLIS -t plants/update -q 1
}

readPlantConfig() {
  configFile=$1
if [ -f "$configFile" ]; then
  echo "$configFile found."

  while IFS='=' read -r key value
  do
    key=$(echo $key | tr '.' '_')
    eval "${key}='${value}'"
  done < "$configFile"
  echo "Plant name   = " ${plant_name}
  echo "MacAddress   = " ${plant_mac}
else
  echo "$configFile not found."
fi
verbose='false'
}

lflag=''
oflag=''
pflag=''
files=''

if [ "$#" -ne 1 ]; then
  echo "sproute.sh -l   - Will list all mac-addresses with Mi Flower"
  echo "sproute.sh -o   - Will generate Openhab items calling java program"
  echo "sproute.sh -p   - Will poll and publish data using mqtt"
fi

while getopts 'lofp' flag; do
  case "${flag}" in
    l) lflag='true' ;;
    o) oflag='true' ;;
    p) pflag='true' ;;
    f) files="${OPTARG}" ;;
    *) error "Unexpected option ${flag}" ;;
  esac
done

if [ "$lflag" == "true" ]; then
  echo "Searching for mi flower firmware 2.6.6"
  ##Hack to restart hci, when kill will stop working otherwise
  #
  sudo hciconfig hci0 down
  sudo hciconfig hci0 up
  # End Hack
  sudo hcitool lescan> $SCAN_RESULT_FILE &
  sleep 5
  sudo pkill --signal SIGINT hcitool
  sudo hciconfig hci0 down
  sudo hciconfig hci0 up
  result=$(sudo timeout 5s hcitool lescan)
  ##Hack to restart hci, when kill will stop working otherwise
  sudo hciconfig hci0 down
  sudo hciconfig hci0 up
  # End Hack
  echo "Firmware 2.6.6"
  sudo cat $SCAN_RESULT_FILE |grep "Flower care"
  echo "Firmware 2.6.2"
  sudo cat $SCAN_RESULT_FILE |grep "Flower mate"
fi

if [ "$oflag" == "true" ]; then
   rm $PLANT_ITEMS_FILE
   java -jar $SPROUTE_JAR $SPROUTE_PROPS -o $PLANT_ITEMS_FILE
   echo "Wrote $PLANT_ITEMS_FILE"
   cat $PLANT_ITEMS_FILE
fi

if [ "$pflag" == "true" ]; then
   PLANT_FILES=`ls ${PLANT_FILES_DIR}/*`
   echo $PLANT_FILES
   for i in $PLANT_FILES; do
      readPlantConfig $i
      plantCheck
   done
fi

Just out of curiousity, could you share the icons you use in your items file? This would make setting up a nice UI easier :smile:

1 Like

Hi I see that you managed to get your sensor working. I am new to openhab so I would like to ask if you could share what needs to be done on the openhab side when I got sproute.sh working?

Thanks

you need to first confirm the server for connect with miflora have bluetooth ability and confirm it’s able to use
after that is quite simple, just follow the step of @Seaside showing,
the instruction from Seaside I found difficult on running his code sproute.sh, first you need to edit the top few line to match your server config, than you can run sproute.sh -l for search miflora device and sproute.sh -p for post mqtt,
so only thing need to do manual is setup items file, you can copy items file from his instruction and modify a little like name and mqtt path, than everything works.

@seaside What is the benfit of running it through the MQTT instead of creating local files and use json on these?

Number miflora_battery "Battery level [%d %%]" <cistern> (miflora) { exec="<[cat /home/pi/miflora.json:60000:JSONPATH($.battery)]" }

but it also needs to run this right?

python /home/pi/miflora.py C4:7C:8D:60:9E:08 miflora.json

And why create files at all, why cant the python just take in parameters(bluetootk,json object) and just return the value?

#Read data from Xiaomi flower monitor, tested on firmware version 2.6.6

import sys
from gattlib import GATTRequester, GATTResponse
from struct import *


address = sys.argv[1]
requester = GATTRequester(address)
#Read battery and firmware version attribute
data=requester.read_by_handle(0x0038)[0]
battery, version = unpack('<B6s',data)
print "Battery level:",battery,"%"
print "Firmware version:",version
#Enable real-time data reading
requester.write_by_handle(0x0033, str(bytearray([0xa0, 0x1f])))
#Read plant data
data=requester.read_by_handle(0x0035)[0]
temperature, sunlight, moisture, fertility = unpack('<hxIBHxxxxxx',data)

  
 if sys.argv[2]="Temperature" then return temperature

One thing that comes to mind is that when going the MQTT route, I can have a small Pi just next to my plants which feeds the MQTT server, and the main Pi with the full openHab installation is in my basement where all the other home automation stuff lives.

Another reason, I don’t like to launch the json interpreter six times to read the six values, every process that is launched consumes some amount of CPU. The same holds true for launching phyton processes. Better launch one process, which pumps all six values into the Queue.

But then, this might be my Unix upbringing, every fork()/system() call immediately leads to suspicion :smile:

Hello,

my question:
I successfully launched the miflora python script together with mqtt 
 everything works well.
In addition I want to integrate FLIC - buttons with the flicd daemon.
Both works well 
 BUT not together :cry:

Does anybody has some experience?

Regards
Jörg

@skatun

Sorry been busy moving to a new house.
Yes I suppose you can use json. The reason why I use MQTT is because its lightweight, designed for machine 2 machine communication. Also I have a total of 4 pies scattered in my house, they all send data to openhab, and in that context MQTT is really fit for the job.

If you really want to go with json, you could mount a network share (samba or nfs), and write files from the different pies in the same place, and then use openhab to read all those files. I don’t think that solution is as clean as using MQTT.

In general I tend to use MQTT for all m2m communication.

Regards, S

1 Like

Well they are all connected to the rpi that is running OH2, thats why I thought it is a bit over kill to set up MQTT broker on that pi as well


I did my example as a tutorial to show different options, and let people use whatever solution fits their requirements best. Having a relay PI to send data over MQTT could be on reason. If you don’t happen to use OpenHAB but something else, having all data on MQTT could be on reason. Or maybe have a small ESP sitting somewhere which is displaying data from MQTT on a small OLED screen.

But you are correct, I am using the JSON method as well.

Hi, thank you verry much for your tutorial.
But I have this problem when I run ‘sudo python3 miflora.py’
It return:
Battery Level : 91%
Firmware version: b’\x102.6.2’
on notification, handle 0x21 -> 00:00:
on notification, handle 0x21 -> 00:00:
on notification, handle 0x21 -> 00:00:

(process:1202): GLib=CRITICAL **: Source ID 4 was not found when attempting to remove it

I have no idea what is happening, this is my first time with Raspberry pi also. Do you knows how to fix this?

Hi,

Unfortunately I don’t know how to fix it. I noticed that it is happening from time to time, but whenever I re-run the script it works for the second time. Can you please check that? Is this a re-occuring issue or just a one off?

Csongor

Hi hamwong,
after a little trial and error I found out, that you need to create a file “sproute.properties” with the path to your plants.
E.g.

sproute.config.location=/home/pi/plants

in that directory you’ll need to have your plant file(s) located.

E.g. if you want to monitor your tomatoes (Solanum lycopersicum) you’ll create a file called

tomatoe.zpc

(.zpc is just an extension used by the java program. At first I thought it’s a kind of zipped file, but it is just plain text.)

The content of the plant file needs to look like this - remember the mac address has to be adjusted to your Xiaomi Miflora sensor address.

plant.name=Tomatoes
plant.mac=22:ff:ef:bc:7d
plant.moist.low=20
plant.moist.high=60
plant.temp.low=8.0
plant.temp.high=32.0
plant.conductivity.low=500
plant.conductivity.high=2000
plant.log.suffix=p0

Great Thanks, I did tried look a quick review on code and I thought was talking about sproute locaitaon.
and of cuz I fail, I really can’t do coding except print"hello world"
sproute.config.location=/home/pi/sproute

Hello!
Where do you take the lower and upper limit?

Thank you for your reply
this problem has been happening everytime I run the file. It’s always return the same error. By the way, I’m using Raspberry Pi model B and raspbian Jessie Lite.

Hi Sergey,
I just took them from the sample files inside the jar. They are located in the folder test/resources.
You just need to extract the jar. The jar is basically a zip file, you may also alter the extension to zip and extract it with your favorite unzip program.
I did not change the values so far, because I also need to experiment a little more, maybe other plants need different values.
I hope this will answer your question.