给
树莓派4B
装了Ubuntu20.04
当做便携服务器在使用,为了便携,自然是不接网线使用WiFi
,不接显示屏使用SSH远程连接工具
,那就面临一个问题,在没有固定分配IP的情况下,怎么不通过接显示器获取IP用来远程连接呢?搜索看了下,最方便的应该就是开机自启自动显示IP等信息
了。
- Ubuntu20.04 Python环境下,获取IP、磁盘存储占用等配置信息
- 获取IP
import socket def getIP(): ip = socket.gethostbyname(socket.gethostname()) return 'IP:'+ str(ip)
- 获取MAC
import uuid def getMAC(): node = uuid.getnode() macHex = uuid.UUID(int=node).hex[-12:] MAC = [] for i in range(len(macHex))[::2]: MAC.append(macHex[i:i+2]) MAC =':'.join(MAC) return 'MAC:' + str(MAC)
- 获取磁盘占用
import os def getDisk(): disk = os.statvfs("/") disk_size = disk.f_bsize * disk.f_blocks / (1024 ** 3) # 1G = 1024M 1M = 1024KB 1KB = 1024bytes sizeStr = str("%s" % format(disk_size, '.2f')) disk_used = disk.f_bsize * (disk.f_blocks - disk.f_bfree) / (1024 ** 3) usedStr = str("%s" % format(disk_used, '.2f')) return usedStr + "/" + sizeStr
- 接入OLED屏幕,点亮屏幕显示
- 接线参考开机自启动OLED屏显示
GND:电源地(Ground)
VCC:电源正(3.3V-5V)
SCL:IIC时钟
SDA:IIC数据
连接树莓派:GND接Gound,VCC接5V,SCL接BCM3(SCL),SDA接BCM2(SDA)。
- 代码参考树莓派通过 I2C 驱动 LCD1602 液晶屏,在文件夹内写入驱动程序
LCD1602.py
import time import smbus BUS = smbus.SMBus(1) LCD_ADDR = 0x27 BLEN = 1 #turn on/off background light def turn_light(key): global BLEN BLEN = key if key ==1 : BUS.write_byte(LCD_ADDR ,0x08) else: BUS.write_byte(LCD_ADDR ,0x00) def write_word(addr, data): global BLEN temp = data if BLEN == 1: temp |= 0x08 else: temp &= 0xF7 BUS.write_byte(addr ,temp) def send_command(comm): # Send bit7-4 firstly buf = comm & 0xF0 buf |= 0x04 # RS = 0, RW = 0, EN = 1 write_word(LCD_ADDR ,buf) time.sleep(0.002) buf &= 0xFB # Make EN = 0 write_word(LCD_ADDR ,buf) # Send bit3-0 secondly buf = (comm & 0x0F) << 4 buf |= 0x04 # RS = 0, RW = 0, EN = 1 write_word(LCD_ADDR ,buf) time.sleep(0.002) buf &= 0xFB # Make EN = 0 write_word(LCD_ADDR ,buf) def send_data(data): # Send bit7-4 firstly buf = data & 0xF0 buf |= 0x05 # RS = 1, RW = 0, EN = 1 write_word(LCD_ADDR ,buf) time.sleep(0.002) buf &= 0xFB # Make EN = 0 write_word(LCD_ADDR ,buf) # Send bit3-0 secondly buf = (data & 0x0F) << 4 buf |= 0x05 # RS = 1, RW = 0, EN = 1 write_word(LCD_ADDR ,buf) time.sleep(0.002) buf &= 0xFB # Make EN = 0 write_word(LCD_ADDR ,buf) def init_lcd(): try: send_command(0x33) # Must initialize to 8-line mode at first time.sleep(0.005) send_command(0x32) # Then initialize to 4-line mode time.sleep(0.005) send_command(0x28) # 2 Lines & 5*7 dots time.sleep(0.005) send_command(0x0C) # Enable display without cursor time.sleep(0.005) send_command(0x01) # Clear Screen BUS.write_byte(LCD_ADDR ,0x08) except: return False else: return True def clear_lcd(): send_command(0x01) # Clear Screen def print_lcd(x, y, str): if x < 0: x = 0 if x > 15: x = 15 if y <0: y = 0 if y > 1: y = 1 # Move cursor addr = 0x80 + 0x40 * y + x send_command(addr) for chr in str: send_data(ord(chr)) if __name__ == '__main__': init_lcd() print_lcd(0, 0, 'Hello, world!')
- 点亮显示
#!/user/bin/env python import smbus import datetime import time import pytz as pytz import sys import LCD1602 as LCD import os import socket import uuid def getIP(): ip = socket.gethostbyname(socket.gethostname()) return 'IP:'+ str(ip) def getMAC(): node = uuid.getnode() macHex = uuid.UUID(int=node).hex[-12:] MAC = [] for i in range(len(macHex))[::2]: MAC.append(macHex[i:i+2]) MAC =':'.join(MAC) return 'MAC:' + str(MAC) def getDisk(): disk = os.statvfs("/") disk_size = disk.f_bsize * disk.f_blocks / (1024 ** 3) # 1G = 1024M 1M = 1024KB 1KB = 1024bytes sizeStr = str("%s" % format(disk_size, '.2f')) disk_used = disk.f_bsize * (disk.f_blocks - disk.f_bfree) / (1024 ** 3) usedStr = str("%s" % format(disk_used, '.2f')) return usedStr + "/" + sizeStr if __name__ == '__main__': LCD.init_lcd() time.sleep(1) ipStr = getIP() LCD.print_lcd(0, 0, ipStr) for x in range(1, 4): LCD.turn_light(0) LCD.print_lcd(4, 1, 'LIGHT OFF') time.sleep(0.5) LCD.turn_light(1) LCD.print_lcd(4, 1, 'LIGHT ON ') time.sleep(0.5) LCD.turn_light(0) while True: tz = pytz.timezone('Asia/Shanghai') # 东八区 show = getDisk() + " " + str(datetime.datetime.fromtimestamp(int(time.time()), tz).strftime('%H:%M')) LCD.print_lcd(0, 1, show ) time.sleep(0.2)
- 接线参考开机自启动OLED屏显示
- 设置开机自启动
- 建立rc-local.service文件,如果存在的话可以不用创建
sudo vim /etc/systemd/system/rc-local.service
- 将下列内容复制进rc-local.service文件
[Unit] Description=/etc/rc.local Compatibility ConditionPathExists=/etc/rc.local [Service] Type=forking ExecStart=/etc/rc.local start TimeoutSec=0 StandardOutput=tty RemainAfterExit=yes SysVStartPriority=99 [Install] WantedBy=multi-user.target
- 创建文件rc.local
sudo vim /etc/rc.local
- 将下列内容复制进rc.local文件(对应脚本的位置和虚拟环境的位置自行修改)
#!/bin/sh -e ## ## rc.local ## ## This script is executed at the end of each multiuser runlevel. ## Make sure that the script will "exit 0" on success or any other ## value on error. ## ## In order to enable or disable this script just change the execution ## bits. ## ## By default this script does nothing. # eaudio --start nohup /root/.virtualenvs/dj3/bin/python3 -u /opt/pi/getpi.py > test.out 2>&1 &
- 给rc.local加上权限
sudo chmod +x /etc/rc.local
- 启用服务
sudo systemctl enable rc-local
- 启动服务并检查状态
sudo systemctl start rc-local.service
sudo systemctl status rc-local.service
- 重启系统测试
reboot
- 建立rc-local.service文件,如果存在的话可以不用创建