简体   繁体   English

将数据从 I2C 传感器发送到本地 SQL 数据库的 Python 代码

[英]Python code to send data from I2C sensor to a local SQL database

I am working on a system of I2C sensors connected together and communicating to a raspberry pi4B.我正在研究连接在一起并与树莓派 pi4B 通信的 I2C 传感器系统。 With the code below I am able to save the measurements in a excel file.使用下面的代码,我可以将测量结果保存在 excel 文件中。 I would like to store them in a table inside a sql database that I have created locally on my laptop.我想将它们存储在我在笔记本电脑上本地创建的 sql 数据库内的表中。 What should I change in this code?我应该在此代码中更改什么?

import time
import datetime
import bme680
from as7262 import AS7262
from datetime import date
from openpyxl import load_workbook

as7262 = AS7262()

as7262.set_gain(1) # 1, 3.7, 16, 64
as7262.set_integration_time(10) #1 to 255 x 2.8ms exposure
#mode 0 - bank 1 only continuous, mode 1 - bank 2 only continuous, mode 2 - both banks continuous, mode 3 - both banks single read 
as7262.set_measurement_mode(2) #2 all colours continuous
as7262.set_illumination_led_current(12.5) #12.5mA 25mA 50mA 100mA
as7262.set_illumination_led(0)

sensor_bme680 = bme680.BME680()

# Load the workbook and select the sheet
wb = load_workbook('/mypath/data.xlsx')
sheet = wb['data_log']

try:
    while True:
        values = as7262.get_calibrated_values() #get values from scan
        spec = [float(i) for i in list(values)] #convert results from string to float
        temperature = round(sensor_bme680.data.temperature, 2)
        pressure = round (sensor_bme680.data.pressure, 2)
        humidity = round(sensor_bme680.data.humidity, 2)
        gas_resistance = round(sensor_bme680.data.gas_resistance, 2)
        red_light = round(spec[0], 4)
        orange_light = round(spec[1], 4)
        yellow_light = round(spec[2], 4)
        green_light = round(spec[3], 4)
        blue_light = round(spec[4], 4)
        violet_light = round(spec[5], 4)
        today = date.today()
        now = datetime.datetime.now().time()
        
        # Inform the user!
        print('Adding this data to the spreadsheet:')
        print(today)
        print(now)
        print('{}*C {}hPa {}% {}res microM microM microM microM microM microM'.format(temperature, pressure, humidity, gas_resistance, red_light,orange_light,yellow_light,green_light,blue_light,violet_light))


        # Append data to the spreadsheet
        row = (today, now, temperature, pressure, humidity, gas_resistance, red_light,orange_light,yellow_light,green_light,blue_light,violet_light)
        sheet.append(row)
        
        #Save the workbook
        wb.save('/home/pi/Documents/sensors/data.xlsx')
        # Wait for 10 minutes seconds (600 seconds)
        time.sleep(10)

finally:
    # Make sure the workbook is saved!
    wb.save('/mypath/data.xlsx')
    
    print('Goodbye!')

For directly posting data in Database instead of Excel sheet you can use mariadb in python.要直接在数据库而不是 Excel 工作表中发布数据,您可以在 python 中使用 mariadb。

First download mariadb in RaspberryPi and setup a database with desired tables.首先在 RaspberryPi 中下载 mariadb 并设置一个包含所需表的数据库。 Then you can add below mentioned code for connection to your program.然后您可以添加下面提到的代码以连接到您的程序。

for example:

mariadb_connection = mariadb.connect(user='username', password='password', database='databasename')
cursor= mariadb_connection.cursor()
Query1="Your query that you want to run"
cursor.execute(Query1,"anyvalue that will be passed")
mariadb_connection.commit();

I personally like to work with sqlalchemy in most cases when interacting with databases from python.我个人喜欢在大多数情况下使用 sqlalchemy 与来自 python 的数据库进行交互。 it represents table-definitions as classes and for adding a row to your db, you only have to create an object of your class and add it via sqlalchemy commands to database.它将表定义表示为类,并且要向数据库中添加一行,您只需创建类的对象并通过 sqlalchemy 命令将其添加到数据库中。 Therefore, you have to define your database in python, so that its structure is known to your code.因此,您必须在 python 中定义您的数据库,以便您的代码知道它的结构。

for an example, I assume we only have one table in your database, having the same columns as your excel sheet.例如,我假设您的数据库中只有一个表,与您的 Excel 表具有相同的列。 the definition of your table and creation of your db (a local sqlite db created in the same folder this script is in) would look like this as a script (lets call this script db.py):表的定义和数据库的创建(在此脚本所在的同一文件夹中创建的本地 sqlite 数据库)将如下所示作为脚本(我们将此脚本称为 db.py):

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Float, DateTime, Date
from sqlalchemy import create_engine

engine = create_engine('sqlite:///foo.db')
Base = declarative_base()

class Example(Base):
    id = Column(Integer, primary_key=True)
    temperature = Column(Float)
    humidity = Column(Float)
    .
    .
    # your other variables
    .
    .
    today = Column(Date)
    now = Column(DateTime)
    
if __name__ == '__main__':
    Base.metadata.create_all(engine)

after running the above script, in your script (the one you posted) you have to import your Example class and replace the line where you add a row to excel with one where you add an Example object (after creating it) to your database.运行上述脚本后,在您的脚本(您发布的那个)中,您必须导入您的Example类,并将您添加一行到 excel 的行替换为您向数据库添加Example对象(创建后)的行。

import time
import datetime
import bme680
from as7262 import AS7262
from datetime import date
from openpyxl import load_workbook
from db import Example
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# create a session for writing to your db
engine = create_engine('sqlite:///foo.db')
Session = sessionmaker(bind=engine)
session = Session()

as7262 = AS7262()

as7262.set_gain(1) # 1, 3.7, 16, 64
as7262.set_integration_time(10) #1 to 255 x 2.8ms exposure
#mode 0 - bank 1 only continuous, mode 1 - bank 2 only continuous, mode 2 - both banks continuous, mode 3 - both banks single read 
as7262.set_measurement_mode(2) #2 all colours continuous
as7262.set_illumination_led_current(12.5) #12.5mA 25mA 50mA 100mA
as7262.set_illumination_led(0)

sensor_bme680 = bme680.BME680()



try:
    while True:

        example_object = Example(
                temperature = round(sensor_bme680.data.temperature, 2),
                humidity = round(sensor_bme680.data.humidity, 2),
                .
                .
                # you other attributes
                .
                .
                today = date.today(),
                now = datetime.datetime.now().time())
        
        # Inform the user!
        print('Adding this data to the spreadsheet:')
        print(today)
        print(now)
        print('{}*C {}hPa {}% {}res microM microM microM microM microM microM'.format(example_object.temperature, example_object.pressure, example_object.humidity, example_object.gas_resistance, example_object.red_light,example_object.orange_light,example_object.yellow_light,example_object.green_light,example_object.blue_light,example_object.violet_light))


        # Add object to database
        session.add(example_object)
        session.commit()

        
        

finally:
    
    print('Goodbye!')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM