Raspberry Pi in IoT

     

    Sensor                                                       Raspberry Pi

obtain and convert raw values 

mport pexpect
import sys
import time

bluetooth_adr = "54:6C:0E:52:FF:08"

def floatfromhex(h):
    t = float.fromhex(h)
    if t > float.fromhex('7FFF'):
       t = -(float.fromhex('FFFF') - t)
       pass
    return t


def calcTmpTarget(objT,ambT):
    m_tmpAmb = ambT/128.0
    Vobj2 = objT * 0.00000015625
    Tdie2 = m_tmpAmb + 273.15
    S0 = 6.4E-14
    a1 = 1.75E-3
    a2 = -1.678E-5
    b0 = -2.94E-5
    b1 = -5.7E-7
    b2 = 4.63E-9
    c2 = 13.4
    Tref = 298.15
    S = S0 * (1+a1*(Tdie2-Tref)+a2*pow((Tdie2-Tref),2))
    Vos = b0 + b1 *(Tdie2 - Tref) +b2*pow((Tdie2-Tref),2)
    fObj = (Vobj2 - Vos) + c2*pow((Vobj2 - Vos),2)
    tObj = pow(pow(Tdie2,4) + (fObj/S),.25)
    tObj = (tObj - 273.15)
    return "%.2f" % tObj

tool = pexpect.spawn('gatttool -b ' + bluetooth_adr + ' --interactive')
tool.expect('.*\[LE\]>', timeout=600)
print ("Preparing to connect. You might need to press the side button...")
tool.sendline('connect')
tool.expect('Connection successful.*\[LE\]>')

tool.sendline('char-write-cmd 0x27 01')
tool.expect('\[LE\]>')

print ("please input the number of loops you want")
n = input()
threshold = 83.0
for i in range(1,int(n)) :
    tool.sendline('char-read-hnd 0x24')
    tool.expect('descriptor: .*')
    rval = tool.after.split()
    objT = floatfromhex(str(rval[2] + rval[1])[2:6])
    ambT = floatfromhex(str(rval[4] + rval[3])[2:6])
    IRtemp = calcTmpTarget(objT,ambT)
    IRtemp2 = (float(IRtemp) - 32) * 5 / 9
    if(float(IRtemp) > threshold):
       print ( "the temperature is too high")
    print (bluetooth_adr, ": the Fahrenheit is :" , IRtemp, " the Celsius is %.2f:" % IRtemp2)

    time.sleep(5)

using the BluePy Library to Interact with SensorTag 

from bluepy.btle import BTLEException
from bluepy import sensortag
from bluepy.sensortag import SensorTag
import time
import datetime

SENSORTAG_ADDRESS = "54:6C:0E:52:FF:08"

def enable_sensors(tag):
    tag.IRtemperature.enable()
    tag.barometer.enable()
    tag.lightmeter.enable()
    tag.gyroscope.enable()
    time.sleep(1.0)

def disable_sensors(tag):
    tag.IRtemperature.disable()
    tag.lightmeter.disable()
    tag.barometer.disable()
    tag.gyroscope.disable()

def get_readings(tag):

    try:
        enable_sensors(tag)
        readings = {}
        readings["ir_temp_amb"],readings["ir_temp_obj"] = tag.IRtemperature.read()
        readings["baro_temp"],readings["pressure"] = tag.barometer.read()
        readings["light"] = tag.lightmeter.read()
        readings["gyro_x"],readings["gyro_y"],readings["gyro_z"] = tag.gyroscope.read()
        readings = {key: round(value,2) for key, value in readings.items()}
        return readings

    except BTLEException as e:

  print ("Unable to take sensor readings.")
        print(e)
        return {}

def  reconnect(tag):
    try:
        tag.connect(tag.deviceAddr,tag.addrType)

    except Exception as e:
        print ("Unable to reconnect to SensorTag.")
        raise e

print('Connecting to {}'.format(SENSORTAG_ADDRESS))
tag = SensorTag(SENSORTAG_ADDRESS)

while True:
   
    readings = get_readings(tag)
   
    if not readings:
        print ("SensorTag disconnected. Reconnecting.")
        reconnect(tag)
        continue
   
    print("Time:\t{}".format(datetime.datetime.now()))
    print("Temperature: ", readings["ir_temp_obj"])
    print("Pressure: ",readings["pressure"])
    print("Light: ",readings["light"])
    print("Gyro_x: ",readings["gyro_x"])
    print("Gyro_y: ",readings["gyro_y"])
    print("Gyro_z: ",readings["gyro_z"])
    print("--------------------------------------")

Sending an MQTT Message to Another Machine

To subscribe to a new MQTT topic on the Raspberry Pi:

( to get your IP address, you can use the command "ifconfig"

mosquitto_sub -h 192.168.2.16 -t pi/test

To publish a message using the following command:

mosquitto_pub -h 192.168.2.16 -t pi/test -m “Wakanda Forever!”

Using python instead:

First,create a text file called config.ini and save it to your Rasberry Pi:

[MQTT]

host = 192.168.2.26
port = 1883
prefix = test/topic

Then:

import paho.mqtt.client as mosquitto
import ConfigParser
import time

config_file = "config.ini"

if __name__ == "__main__":
  try:
     config = ConfigParser.ConfigParser()
     config.readfp(open(config_file,"r"))
  except IOError as e:
     print e
 
  try:
    host = config.get("MQTT","host")
  except ConfigParser.NoOptionError:
    host = os.getenv("MQTT_BROKER","localhost")
  try:
    port = config.getint("MQTT","port")
  except ConfigParser.NoOptionError:
    port = int(os.getenv("MQTT_BROKER","1883"))
  try:
    prefix = config.get("MQTT","prefix")
  except ConfigParser.NoOptionError:
    prefix = "test/topic"

topic = prefix
mqtt = mosquitto.Mosquitto()
mqtt.connect(host)
mqtt.loop_start()

while True:
    payload = "Hello World!"
    print (topic,payload)
    mqtt.publish(topic,payload,qos=0,retain=False)
    time.sleep(5)

mqtt.loop_stop()
mqtt.disconnect()


  

 use python yourname.py to run

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值