Xiaomi Miflora Sensor Integration

json
xiaomi
miflora
Tags: #<Tag:0x00007f51dfee5218> #<Tag:0x00007f51dfee50b0> #<Tag:0x00007f51dfee4e08>

(Csongor Varga) #1

Hi All,

I know somebody started a similar topic already, but it seems to be unfinished. Let me give you my take on this device and how I did it on Raspberry PI 3. @Seaside has posted another approach, please scroll down to post 5 for that.

If you prefer to watch instead of reading, you can also watch my Youtube video on the same:

I took the basics from this website: https://wiki.hackerspace.pl/projects:xiaomi-flora
The important takeaway is that Xiaomi can update the firmware on Miflora over the mobile app and they changed how BT communication works in the past. So the below code currently works with firmware 2.6.6. I uninstalled the app from my phone, just to make sure the device is not getting updated again.

Step 1: Python code to read the data from the sensor and save in in a text file and push it to MQTT. You can decide to use the file or MQTT method as per your preference. Don’t forget to update the IP and user details in the MQTT code.

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

import sys
from gattlib import GATTRequester, GATTResponse
from struct import *
import paho.mqtt.client as mqtt

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)
print "Light intensity:",sunlight,"lux"
print "Temperature:",temperature/10.,"C"
print "Soil moisture:",moisture,"%"
print "Soil fertility:",fertility,"uS/cm"

#Sometimes the version contains some funny charcters which throws off the JSON processing. Cleaning string
temp = version
version = " "
for x in temp:
    if x == ".":
        version = version + "."
    if x >= "0" and x <="9":
            version = version + x
version = version.strip()

# Saving information in text file in JSON format
json_file = open(sys.argv[2],"w")
json_file.write("{ \"battery\" : " + str(battery) + ", \"version\" : \"" + version + "\", \"sunlight\" : " + str(sunlight) + ", \"temperature\" : " + str(temperature/10.) + ", \"moisture\" : " + str(moisture) + ", \"fertility\" : " + str(fertility) + " }")
json_file.close()
# End Json file export

# Publishing the results to MQTT
mqttc = mqtt.Client("miflora")
mqttc.username_pw_set("<your userid>","<your password>")
mqttc.connect("<mqtt ip>", 1883)
mqttc.publish("/home/miflora", "{ \"battery\" : " + str(battery) + ", \"version\" : \"" + version + "\", \"sunlight\" : " + str(sunlight) + ", \"temperature\" : " + str(temperature/10.) + ", \"moisture\" : " + str(moisture) + ", \"fertility\" : " + str(fertility) + " }")
mqttc.loop(2)
# End of MQTT section

Step 2: Get the ID of your miflora device. Execute hcitool lescan on the pi. The default name for Miflora is “Flower Care”.

Step 3: Schedule a cron job to read the Miflora. I scheduled my every 15 minutes. First parameter of the python script is the BT ID of Miflora, second is the file to create. It is running for about 1 months now, no drop in the battery level so far. Remember to change the BT ID to yours.

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

If it all goes well, you should have something like this in the json file (and of course same published to MQTT):

{ "battery" : 100, "version" : "2.6.6", "sunlight" : 5841, "temperature" : 24.5, "moisture" : 5, "fertility" : 41 }

I noticed that in some cases Miflora does not return values properly. I don’t know the reason for that, but whenever if fails, it works just fine the next time.

Step 4: Items configuration:

// Xiaomi miflora
Number miflora_battery "Battery level [%d %%]" <cistern> (miflora) { exec="<[cat /home/pi/miflora.json:60000:JSONPATH($.battery)]" }
String mi_flora_version "Firmware version [%s]" <key> { exec="<[cat /home/pi/miflora.json:60000:JSONPATH($.version)]" }
Number miflora_sunlight "Sunlight [%d lux]" <sun> (miflora) { exec="<[cat /home/pi/miflora.json:60000:JSONPATH($.sunlight)]" }
Number miflora_temperature "Temperature [%.1f °C]" <temperature> (miflora) { exec="<[cat /home/pi/miflora.json:60000:JSONPATH($.temperature)]" }
Number miflora_moisture "Soil moisture [%d %%]" <water> (miflora) { exec="<[cat /home/pi/miflora.json:60000:JSONPATH($.moisture)]" }
Number miflora_fertility "Soil fertility [%d uS/cm]" <grass> (miflora) { exec="<[cat /home/pi/miflora.json:60000:JSONPATH($.fertility)]" }

As you can see I use the transformation to read the variables from the JSON data. I added the Number items to same group in order to plot them on the chart. For some reason it is not yet working for me.

Step 5: Sitemap:

Text label="Xiaomi MiFlora" icon="energy" {
    Text item=miflora_battery
    Text item=mi_flora_version
    Text item=miflora_sunlight
    Text item=miflora_temperature
    Text item=miflora_moisture
    Text item=miflora_fertility
    Switch item=Chart_Period mappings=[0="1h", 1="4h", 2="8h", 3="12h", 4="24h"]
    Chart  item=miflora period=h   refresh=60000 visibility=[Chart_Period==0, Chart_Period=="Uninitialized"]
    Chart  item=miflora period=4h  refresh=60000 visibility=[Chart_Period==1]
    Chart  item=miflora period=8h  refresh=60000 visibility=[Chart_Period==2]
    Chart  item=miflora period=12h refresh=60000 visibility=[Chart_Period==3]
    Chart  item=miflora period=D   refresh=60000 visibility=[Chart_Period==4]
}

The sitemap is straight forward. The chart is not showing for me for some reason, so you have to fix that for yourself. I added miflora* : strategy = everyMinute, restoreOnStartup to the persistence, but still no change.

This is my solution in the nutshell. It is working for me just fine. I am reading the data from my sensor over the last month without any issues. I have also done the integration into NodeRed using MQTT.

Cheers,
Csongor


Xiaomi Mi Flora Plant Sensor MQTT Client/Daemon
( ) #2

Hey @Csongor_Varga,
nice one :wink: As I said in the other thread I bought three of these a few weeks/months back but didn’t get around to test them. I’ll definitely do that now!

I’ve updated your posting to color highlight your python code. I also moved the video up as I really liked it :wink: I hope that’s okay, otherwise just revert that change.

It’s a shame that we have two Xiaomi Miflora tutorials now. Quite a coincidence… I would rather see one thread with an active discussion instead of two or one dying away because of the other. Do you see any chance to merge your thread with the other one? You could post your Posting beneath the other one or arrange a merge with @Seaside!? Please do not feel obligated to do so, it’s just an idea.


(Csongor Varga) #3

Hi Thom,

Thanks for your comments. To be honest, I did not even see @Seaside post, he did his today and I did mine yesterday evening. I was referring to another topic called “Plant sensor” which started the same discussion but not completed. I started a new topic with a more specific title so people find it more easily. But I agree that mine and @Seaside could be merged. But I don’t know how to do that, or what would be the best way doing that.

I have also seen the module he is using, and I wonder if that has been updated to the new communication method which was introduced in firmware version 2.6.6.

Maybe you can test that out now :smile:


(Seaside) #4

Hi!

The Miflora (https://github.com/open-homeautomation/miflora/tree/master/dist) is working with firmware 2.6.6 and 2.6.2, I created a topic of its own because the solution is rather cumbersome I’m using python, java, bash and other libraries as well as generating the .items-file, which right now use a rather specific format suited for my needs.

We can definitely merge topics, I can add it to this thread if you like a delete my post. As an alternative solution.

Regards, S


Xiaomi Flower Care Smart Monitor
(Seaside) #5

Moving from other topic.

Here is an alternative way of getting MiFlora plant sensor data into openhab:

There are several threads about this already. I’m posting my setup,
it can probably be labeled as hack, it’s not clean, it’s not beautiful, it’s not easy.
However it works for me, and it’s easy to maintain.

First This is the monitor I’m talking about
http://xiaomi-mi.com/smart-home/xiaomi-huahuacacao-flower-care-smart-monitor/
http://xiaomi-mi.com/uploads/CatalogueImage/pvm_xiaomi-flower-monitor-02_14361_1466174108.jpg

It can be bought on ebay aliexpress and similar, I payed 11 euros a piece on aliexpress.

This thing transfers data using Bluetooth (BT). BT is short ranged, typically you will have plants/flowers scattered around your house on different floors and whatnot.
Therefor I’m using RPis (2-3) to collect data and to poll the devices.
The RPI:s will then post data to Openhab using MQTT.

Source code in java, bash script is available here:
(Extract them from the jar file if you wish to alter)
http://www.zoidberg.se/pub/sproute.jar

Java source files (they are included in the jar as well):
http://www.zoidberg.se/pub/SprouteConfig.java
http://www.zoidberg.se/pub/Sproute.java
http://www.zoidberg.se/pub/PlantConfig.java

  1. Get some RPI or similar
  2. Install Bluetooth dongle or use the built in in RPi3 (not tested this)
    https://www.raspberrypi.org/learning/robo-butler/bluetooth-setup/
  3. Install Java 8
    http://www.rpiblog.com/2014/03/installing-oracle-jdk-8-on-raspberry-pi.html
  4. Install mqtt clients: sudo apt-get install mosquitto-clients
  5. Install git: sudo apt-get install git
  6. Install python3
    sudo apt-get install python3
    sudo apt-get install python3-pip
    sudo apt-get install python3-gattlib (or sudo pip3 install gattlib)
  7. Install miflora python library: https://github.com/open-homeautomation/miflora
    git clone https://github.com/open-homeautomation/miflora
    (I’m not the author of miflora)
  8. Build it, or use the build source inside the repo
  9. Building (./build.sh)
  10. Verify that the lib works by invoking python3 demo.py (change the macaddress inside)

Add this python script to miflora:

import sys
import time
import datetime

from miflora.miflora_poller import MiFloraPoller, \
    MI_CONDUCTIVITY, MI_MOISTURE, MI_LIGHT, MI_TEMPERATURE

poller = MiFloraPoller(str(sys.argv[1]))
now = time.time()
dtnow=datetime.datetime.fromtimestamp(now)
millis = int(round(now * 1000))
yyyymmddhhmmss =  datetime.datetime.strftime(dtnow, '%Y-%m-%d %H:%M:%S')

temp = poller.parameter_value("temperature")
moist = poller.parameter_value(MI_MOISTURE)
light = poller.parameter_value(MI_LIGHT)
cond = poller.parameter_value(MI_CONDUCTIVITY)
battery = poller.battery_level()

print(yyyymmddhhmmss + " C: {:.2f} M: {:d} L: {:d} CD: {:d} B: {:d}".format(temp, moist, light, cond, battery) + " time:" +  str(millis))

Edit the sproute.sh file (located inside the jar if you want to extract it):
Change the parameters on top so the locations are correct:

#!/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

  1. Check your plants with this command:
pi@colibri:~/plants $ /sbin/sproute.sh -l
Searching for mi flower firmware 2.6.6
Firmware 2.6.6
C4:7C:8D:61:CB:75 Flower care
C4:7C:8D:61:CD:11 Flower care
Firmware 2.6.2
C4:7C:8D:62:51:51 Flower mate
  1. Create plants file inside the plant folder (see sh-script)
i@colibri:~/plants $ cat benji.zpc 
plant.name=Benji
plant.mac=C4:7C:8D:61:CB:75
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

Create openhab items:
This will create openhab items for all plants you have.

pi@colibri:~/plants $ /sbin/sproute.sh -o
Wrote file successfully: /home/pi/plants.items
Wrote /home/pi/plants.items
Group Plants
Group PlantTemperature
Group PlantMoisture
Group PlantLight
Group PlantConductivity
Group PlantBattery

Number   PlantsUpdate          "Plants Updated [%s]"  <clock> (Plants) { mqtt="<[mosquitto:plants/update:state:default]" }

Group    PlantBenji             "Plant Benji"               <plant2>        (Plants)
Number   PlantBenjiTemperature  "Benji  [%.2f °C]"       <ptemp>  (Temperature, PlantTemperature, PlantBenji) { mqtt="<[mosquitto:plants/benji/temp:state:default]" }
Number   PlantBenjiTempHigh     "Benji [%.2f °C]"                          (PlantBenji)  { mqtt="<[mosquitto:plants/benji/temphigh:state:default]" }
Number   PlantBenjiTempLow     "Benji [%.2f °C]"                          (PlantBenji)  { mqtt="<[mosquitto:plants/benji/templow:state:default]" }
Number   PlantBenjiMoisture     "Benji [%d %%]"             <pmoisture>     (PlantMoisture, PlantBenji)     { mqtt="<[mosquitto:plants/benji/moist:state:default]" }
Number   PlantBenjiMoistLow     "Benji [%d %%]"             <pmoisture>     (PlantMoisture, PlantBenji)     { mqtt="<[mosquitto:plants/benji/moistlow:state:default]" }
Number   PlantBenjiMoistHigh    "Benji [%d %%]"             <pmoisture>     (PlantMoisture, PlantBenji)     { mqtt="<[mosquitto:plants/benji/moisthigh:state:default]" }
Switch   PlantBenjiMoistWarn    "Benji Moisture Level Warning"                                  (PlantMoisture, PlantBenji) 
Number   PlantBenjiConductivity "Benji [%d uS/cm]"          <pconduct> (PlantConductivity, PlantBenji) { mqtt="<[mosquitto:plants/benji/cond:state:default]" }
Number   PlantBenjiConductHigh  "Benji [%d uS/cm]"           (PlantConductivity, PlantBenji) { mqtt="<[mosquitto:plants/benji/condhigh:state:default]" }
Number   PlantBenjiConductLow   "Benji [%d uS/cm]"           (PlantConductivity, PlantBenji) { mqtt="<[mosquitto:plants/benji/condlow:state:default]" }
Switch   PlantBenjiConductWarn    "Benji Conductivity Level Warning"                                  (PlantConductivity, PlantBenji) 
Number   PlantBenjiLight        "Benji [%d Lux]"            <psun>          (PlantLight, PlantBenji)        { mqtt="<[mosquitto:plants/benji/light:state:default]" }
Number   PlantBenjiBattery      "Benji [%d %%]"             <pbattery>      (PlantBattery, Battery, PlantBenji)       { mqtt="<[mosquitto:plants/benji/battery:state:default]" }
DateTime PlantBenjiLastUpdate   "Last Update [%1$tY-%1$tm-%1$td %1$tH:%1$tM]" <clock>        (PlantLastUpdate, PlantBenji)
  1. Send result to openhab
pi@colibri:~/plants $ /sbin/sproute.sh -p
/home/pi/plants/benji.zpc found.
Plant name   =  Benji
MacAddress   =  C4:7C:8D:61:CB:75
Published p0: TEMP=20.60 MOIST=79 LIGHT=2185 COND=3471 BATTERY=92
Published COND_LOW=500 COND_HIGH=2000

In openhab you can add the following warning to send out notification when to water the plant:

import java.util.Map
import java.util.HashMap
val String LOG_PLANTS = "Plants"
var Map<String, Integer> mNameToMoistLow = new HashMap<String, Integer>()
var Map<String, Integer> mNameToMoistHigh = new HashMap<String, Integer>()

val Functions$Function2 populateMoistHighLow = [Map<String, Integer> mNameToMoistLow, Map<String, Integer> mNameToMoistHigh |
     mNameToMoistLow.clear()
     mNameToMoistHigh.clear()
     PlantMoistLow.members.forEach[ moistLow |
        mNameToMoistLow.put(moistLow.label, new Integer(moistLow.state.toString))
     ]
   
     PlantMoistHigh.members.forEach[ moistHigh |
        mNameToMoistHigh.put(moistHigh.label, new Integer(moistHigh.state.toString))
     ]
    
]

rule "PlantThirstyWarning"
when
  Item PlantsUpdate received update
then
  if (mNameToMoistLow == null) {
       mNameToMoistLow = new HashMap()
   }
   if (mNameToMoistHigh == null) {
       mNameToMoistHigh = new HashMap()
   }
   
   if (mNameToMoistLow.empty || mNameToMoistHigh.empty) {
      populateMoistHighLow.apply(mNameToMoistLow, mNameToMoistHigh)
      logInfo(LOG_PLANTS, "Created map for plants high low low:" + mNameToMoistLow + " high: " + mNameToMoistHigh)
   }
   
   logInfo(LOG_PLANTS, "Moisture updated, checking if any plant is thirsty")
   PlantMoist.members.forEach[ moist |
       val int moistLow = mNameToMoistLow.get(moist.label)
       val int moistHigh = mNameToMoistHigh.get(moist.label)
       var int moistValue = (moist.state as DecimalType).intValue
       logInfo("Plants", "Parsed low: " + moistLow + " high: " + moistHigh + " moist: " + moist.state.toString)
       if (moistValue <= moistLow) {
            logInfo(LOG_PLANTS, "Warning plant: " + moist.label + " is Below lower threshold")
            NotifyPlants.postUpdate("My thirsty warning")
       } else if (moistValue >= moistHigh) {
               logInfo(LOG_PLANTS, "Warning plant: " + moist.label + " is above higher threshold")
           } else {
               logInfo(LOG_PLANTS, "Plant is " + moist.label + " is ok on water level")
       }
     ]
end

Edit crontab (I run this every 3 hours)

1  */3  * * *   root    /sbin/sproute.sh -p

So some things

  • I use java to generate the openhab items, why because I know java better than python, and I have limited time.
  • I use bash because I know bash, could be done in python as well.
  • I log each check to a log-file, why because I graph this data with Graphite/Grafana
  • This is a hack, but it enables me to add or remove plants just by creating a plant file, giving the plant a name and specify a mac-address. My goal is to be able to add and change plants on the fly, but without rewriting code.
  • Watering rule is generic and will not have to be altered.
  • Is this solution ugly, yes, but still does the job for me, feel free to change whatever, or perhaps it can inspire to something better :slight_smile:

Nice & easy affordable temperature / light / moisture sensor - Xiaomi Flora
Xiaomi Mi Flora Plant Sensor MQTT Client/Daemon
Plant sensor
(Oliver) #6

Hi. Very excited for this project, great work. I have a few questions in mind. I am planning to use a orange pi zero with built in wifi and a bluetooth dongle. Is there limitations to what dongles are supported? Also how many miflora’s can i connect to one bluetooth dongle?

Thanks in advance, great work


(Csongor Varga) #7

Hi Oliver,

I don’t think there is any limitation. I never used BT before RPi3, but as long as it is a generic BT device and linux has a driver for it, it should work.
There is no limitation in the number of miflora devices used. But ideally you should read them one by one. So BT is only communicating with a single device at any point in time. So I would create a shell script which calls this myflora.py for each device one after the other. And schedule the script in crontab.

Csongor


(Kim Skatun) #8

@Seaside and @Csongor_Varga

I having trouble to get the gattlib installed, this fails: sudo apt-get install python3-gattlib

[00:07:53] pi@openHABianPi:/etc/openhab2/scripts$ sudo apt-get install python3-gattlib
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package python3-gattlib

This works not also:
'pi@openHABianPi:/etc/openhab2/scripts$ sudo pip3 install gattlib
Downloading/unpacking gattlib
Downloading gattlib-0.20150805.tar.gz (1.7MB): 1.7MB downloaded
Running setup.py (path:/tmp/pip-build-1ror2k9t/gattlib/setup.py) egg_info for package gattlib
Traceback (most recent call last):
File “”, line 17, in
File “/tmp/pip-build-1ror2k9t/gattlib/setup.py”, line 12, in
“pkg-config --cflags glib-2.0”.split()).decode(‘utf-8’)
File “/usr/lib/python3.4/subprocess.py”, line 607, in check_output
with Popen(*popenargs, stdout=PIPE, **kwargs) as process:
File “/usr/lib/python3.4/subprocess.py”, line 859, in init
restore_signals, start_new_session)
File “/usr/lib/python3.4/subprocess.py”, line 1457, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'pkg-config’
Complete output from command python setup.py egg_info:
Traceback (most recent call last):

      File "<string>", line 17, in <module>

      File "/tmp/pip-build-1ror2k9t/gattlib/setup.py", line 12, in <module>

        "pkg-config --cflags glib-2.0".split()).decode('utf-8')

      File "/usr/lib/python3.4/subprocess.py", line 607, in check_output

        with Popen(*popenargs, stdout=PIPE, **kwargs) as process:

      File "/usr/lib/python3.4/subprocess.py", line 859, in __init__

        restore_signals, start_new_session)

      File "/usr/lib/python3.4/subprocess.py", line 1457, in _execute_child

        raise child_exception_type(errno_num, err_msg)

    FileNotFoundError: [Errno 2] No such file or directory: 'pkg-config'

    ----------------------------------------
    Cleaning up...
    Command python setup.py egg_info failed with error code 1 in /tmp/pip-build-1ror2k9t/gattlib
    Storing debug log for failure in /root/.pip/pip.log'

which naturally make this fail:

 python /etc/openhab2/scripts/miflora.py C4:7C:8D:61:A5:7D miflora.json
Traceback (most recent call last):
  File "/etc/openhab2/scripts/miflora.py", line 4, in <module>
    from gattlib import GATTRequester, GATTResponse
ImportError: No module named gattlib

(Csongor Varga) #9

I also had issues in the beginning installing gattlib and it was down to the missing dependencies. Somewhere I found a list of the dependencies of this package, but I cannot find that link any more. But I did what you did, apt-get all the dependencies and finally gattlib was installed.

Oh, whilst writing this, I think I found it:
https://bitbucket.org/OscarAcena/pygattlib/src/a858e8626a93cb9b4ad56f3fb980a6517a0702c6/DEPENDS?at=default&fileviewer=file-view-default

Also, this may help:

Sorry, I an quite noob to linux, I spend more time on google than in the terminal.

Regards,
Csongor


(Hakan Tandogan) #10

Thank you for this writeup, yesterday I managed to access my first sensor :slight_smile:

HypriotOS/armv7: pirate@sunflower in ~/miflora on master*
$ python3 demo.py
Getting data from Mi Flora
FW: 2.6.2
Name: Flower mate
Temperature: 23.5
Moisture: 16
Light: 105
Conductivity: 94
Battery: 100

Now all I have to do is to wire everything into openHAB and let my plants send tweets to me and switch the Hue lights to disco mode :smiling_imp:


(Seaside) #11

@skatun

This is what I run:

sudo apt-get install mosquitto-clients python-mosquitto python3 python3-pip pkg-config 
#Painful to install takes time
sudo apt-get install libboost-python-dev 	
sudo apt-get install libboost-thread-dev libbluetooth-dev libglib2.0-dev python-dev git
sudo pip3 install gattlib 

Seems like you are missing pkg-config from your output.

Regards S


(Seaside) #12

I’ve also added a plant moisture level report to Amazon Alexa via Openhab and Alexa-Ha, not sure about the WAF though :slight_smile:


(Kim Skatun) #13

keeps failing,

Command /usr/bin/python3 -c "import setuptools, tokenize;__file__='/tmp/pip-build-6q86beq4/gattlib/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-so6qn807-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /tmp/pip-build-6q86beq4/gattlib
Storing debug log for failure in /root/.pip/pip.log

trying reboot now:)


(Kim Skatun) #14

reboot and this does not work either:
sudo apt-get install python3-gattlib -> E: Unable to locate package python3-gattlib

will keep debugging tomorrow


(Kim Skatun) #15

@Csongor_Varga and @Seaside I am using rpi, which hardware do you guys use? I read something that rpi might not have enough memory to compile the library.


(Seaside) #16

@skatun running on both an rpi 2 and rpi 1 b+.
On the rpi1 I had to increase swap to get it working.
https://www.raspberrypi.org/forums/viewtopic.php?f=26&t=46472

On the rpi 2 that was not needed.

Regards s


(Kim Skatun) #17

Strange I am running rpi2 b+, but I am running openhabian and I think this is stripped down raspian, maybe @ThomDietrich can clarify this, I will try the swap after xmas and get back to u guys…


(Hakan Tandogan) #18

I am running it on a Raspberry Pi 3. As Operating system, I have installed the hypriot distribution ( http://blog.hypriot.com/ ), to which I have added python3 and python3-setuptools via “apt-get install”.

Works fine for my two sensors :smile:


(Csongor Varga) #19

I am also using Rpi3 and after installing the dependencies it was installed without issues. I just used apt-get install.


(Kim Skatun) #20

I know what to wish for xmas then rpi3 or pine64:)