基于树莓派的智能寝室终端(Python练手,运行状况)3

来源:互联网 发布:wget yum 安装包 编辑:程序博客网 时间:2024/05/04 20:08

一、内核温度系统

注:树莓派自带温度传感器

1、http://shumeipai.nxez.com/2014/10/04/get-raspberry-the-current-

status-and-data.html(资料引用)

sudo nano get.py

贴入如下代码:

import os

# Return CPU temperature as a character string                                     

def getCPUtemperature():

    res = os.popen('vcgencmd measure_temp').readline()

    return(res.replace("temp=","").replace("'C\n",""))

# Return RAM information (unit=kb) in a list                                      

# Index 0: total RAM                                                              

# Index 1: used RAM                                                                

# Index 2: free RAM                                                                

def getRAMinfo():

    p = os.popen('free')

    i = 0

    while 1:

        i = i + 1

        line = p.readline()

        if i==2:

            return(line.split()[1:4])

# Return % of CPU used by user as a character string                               

def getCPUuse():

    return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip())) 

# Return information about disk space as a list (unit included)                    

# Index 0: total disk space                                                        

# Index 1: used disk space                                                        

# Index 2: remaining disk space                                                    

# Index 3: percentage of disk used                                                 

def getDiskSpace():

    p = os.popen("df -h /")

    i = 0

    while 1:

        i = i +1

        line = p.readline()

        if i==2:

            return(line.split()[1:5])

# CPU informatiom

CPU_temp = getCPUtemperature()

CPU_usage = getCPUuse()

# RAM information

# Output is in kb, here I convert it in Mb for readability

RAM_stats = getRAMinfo()

RAM_total = round(int(RAM_stats[0]) / 1000,1)

RAM_used = round(int(RAM_stats[1]) / 1000,1)

RAM_free = round(int(RAM_stats[2]) / 1000,1)

# Disk information

DISK_stats = getDiskSpace()

DISK_total = DISK_stats[0]

DISK_used = DISK_stats[1]

DISK_perc = DISK_stats[3]

if __name__ == '__main__':

    print('')

    print('CPU Temperature = '+CPU_temp)

    print('CPU Use = '+CPU_usage)

    print('')

    print('RAM Total = '+str(RAM_total)+' MB')

    print('RAM Used = '+str(RAM_used)+' MB')

    print('RAM Free = '+str(RAM_free)+' MB')

    print('')

    print('DISK Total Space = '+str(DISK_total)+'B')

    print('DISK Used Space = '+str(DISK_used)+'B')

    print('DISK Used Percentage = '+str(DISK_perc))

然后执行:

chmod +x get.py

python get.py

预期输出结果如下:

CPU Temperature = 53.0

CPU Use = 13.5

RAM Total = 497.0 MB

RAM Used = 116.0 MB

RAM Free = 381.0 MB

DISK Total Space = 3.6GB

DISK Used Space = 1.8GB

DISK Used Percentage = 53%

2、定时上传云端:

#!/usr/bin/env python  

# -*- coding: utf-8 -*-  

import requests  

import json  

import time    

def main():  

    fileRecord = open("result.txt", "w")    

    fileRecord.close()  

    while True:  

     # 打开文件  

    file = open("/sys/class/thermal/thermal_zone0/temp")  

   # 读取结果,并转换为浮点数  

    temp = float(file.read()) / 1000  

   # 关闭文件  

    file.close()    

   # 设备URI  

   apiurl = ''  

    # 用户密码,指定上传编码为JSON格式  

   apiheaders = {'U-ApiKey': '', 'content-type': 'application/json'}  

    # 字典类型数据,在post过程中被json.dumps转换为JSON格式字符串{"value": 48.123}  

        payload = {'value': temp}  

        #发送请求  

        r = requests.post(apiurl, headers=apiheaders, data=json.dumps(payload))    

        # 向控制台打印结果  

        fileRecord = open("result.txt", "a")  

        strTime = time.strftime('%Y-%m-%d:%H-%M-%S',time.localtime(time.time()))  

        fileRecord.writelines(strTime + "\n")  

        strTemp = "temp : %.1f" %temp + "\n"  

        fileRecord.writelines(strTemp)  

        fileRecord.writelines(str(r.status_code) + "\n")  

        fileRecord.close()            

        time.sleep(5)    

if __name__ == '__main__':  

    main()  




二、IP地址及网络链接设置

网络链接有以下三种方法:

1、自动获取IP地址

树莓派rasbian系统中默认设置的为动态IP,倘若路由器已设置好,那么接上网线即可上网。

2、设置静态IP

如果想要使用静态IP,那么,步骤如下

首先打开文件修改内容:

sudo nano /etc/network/interfaces

打开后会出现以下程序:

auto lo eth0

iface lo inet loopback

iface eth0 inet dhcp

......

......

这些程序中,代码红色区域本来没有,加上后表示开机自动启动网络回环和网卡,dhcp是表示使用动态ip,在显示屏上可以输入ifconfig用来查看ip地址。

改用静态ip(其中的好处是如果没有显示屏是可以通过putty之类的输入之前设置的静态IP远程登陆树莓派),那么做以下修改:

最后一行改为:

iface eth0 inet static

然后在后面加上:

address 192.168.*.*(ip地址)

netmask 255.255.*.*(子网掩码)

gateway 192.168.*.*(网关)

文件设置完后,就得设置DNS服务器:

选择一款自己喜欢的编辑器,例如nano:

sudo nano /etc/resolv.conf

之后,修改里面的DNS参数

最后重启网络进程:

/etc/init.d/networking restart

注:测试网络是否链接: ping baidu.com  然后看是否有数据传回。


0 0