起因

用templater写了个日记模板,之前是记录创建文件时的温度,
随着使用发现需要回顾本日的气温变化,
如果选择手动去网站查今日天气数据的话:重复性操作太多数据有一定偏差(个人以获取的实时天气为准)
然后就打算写了个脚本一劳永逸.

过程

由于需要一天内定时发送请求获取天气信息,这个在电脑上实现不太可能,
随后便想到了宿舍里的路由器.

其实实现的大致思路并不难

路由器收集一天的天气信息 -> 电脑获取路由器收集到的数据 -> 脚本解析 -> 用obsidian的chart插件完成数据展示

路由器收集信息

之前用node写过获取天气的脚本,思路还是比较简单的.
宿舍的路由器是红米AC2100 性能比较菜,于是打算写一个shell脚本来实现功能
还需要安装一下jq来解析一下json

下面是写好的脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

. /root/weather/config.txt

#如果没填城市编码,则根据ip获取城市编码
if [ -z "$city" ]
then
url="https://restapi.amap.com/v3/ip?key=${key}"
city=$(curl $url | jq ".adcode")
echo "city=\"$city\"" >> config.txt
fi

url="https://restapi.amap.com/v3/weather/weatherInfo?key=${key}&city=${city}&extension=${extensions}"

year=$(date +"%Y")
month=$(date +"%m")
time=$(date +"%Y-%m-%d")
filename="${time}.txt"
path="/www/result/${year}/${month}"
reportTime=$(date +"%Y-%m-%d %H:%M:%S")

#Q:执行之后对应的txt文件没有生成/内容追加
#A:排查发现是路径问题,已修改 path 为绝对路径
mkdir -p ${path}
echo "脚本执行时间: ${reportTime}
下方为内容结果:" >> "${path}/${filename}"
curl ${url} | jq '.lives[0]' >> "${path}/${filename}"
# >>是追加内容,>是覆盖内容
echo "" >> "${path}/${filename}"
1
. /root/weather/config.txt

读取配置文件(openwrt里不支持source,所以改成了 .来达到相同效果)

配置文件里的内容长这样:

1
2
3
key="1145141919810"
extensions="base"
city="410802"

其实也没啥东西.
key 高德的给的APIkey,
extension 实时天气还是未来天气,base是实时天气(未来天气没写,因为用不到)
city 就是城市编码

1
2
3
4
5
6
7
time=$(date +"%Y-%m-%d")
filename="${time}.txt"
path="/www/result/${year}/${month}"
mkdir -p ${path}
curl ${url} | jq '.lives[0]' >> "${path}/${filename}"
# >>是追加内容,>是覆盖内容
echo "" >> "${path}/${filename}"

文件以日期做标题来做区分
然后路径是apache存放文件的位置,就干脆把生成的文件都放到这里了
后来发现openwrt自带简单的http服务,就不用再额外安装apache
把获取到的天气信息放到日期.txt文件里
然后echo ""换行

把写好的脚本放到路由器里面
使用crontab完成定时任务

1
30 6-22/1 * * * /root/weather/getWeather.sh

该命令的意思是
每天6:30-22:30,每个一小时执行一次getWeather.sh脚本
本来是整点发送请求,不过发现获取的数据里的reporttime都是上个小时的半点的数据.
所以设置成半点就可以获取整点的数据了(虽然没啥意义强迫症)

电脑获取信息

解析数据

使用Obsidian的templater插件
用户自定义脚本 实现的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const http = require('http')

const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth()+1).toString().padStart(2,'0');
// 服务器IP
const serverIp = "192.168.1.1"

function getFile(fileName) {
let url = `http://${serverIp}/result/${year}/${month}/${fileName}`
return new Promise((resolve, reject) => {
http.get(url, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
})

res.on('end', () => {
const jsonMatches = data.match(/\{[\s\S]*?\}/g);
if (!jsonMatches) {
console.error('文件中未找到 JSON 数据');
return;
}

let temparr = [];
let timearr = [];
jsonMatches.forEach((jsonString, index) => {
try {
const jsonObject = JSON.parse(jsonString);
//console.log(`第 ${index + 1} 个 JSON 对象:`, jsonObject);
temparr[index] = jsonObject.temperature
//timearr[index] = new Date(jsonObject.reporttime).getHours() + "点"
timearr[index] = jsonObject.reporttime.substring(11,16) //HH-mm
} catch (error) {
console.error(`解析第 ${index + 1} 个 JSON 对象时出错:`, error);
}
});
let result = [temparr,timearr]
//console.log(temparr);
//console.log(timearr);
//resolve(jsonMatches)
resolve(result)
});
}).on('error', (Error) => {
reject(Error);
});
})
}

module.exports=getFile

写的简单的获取天气数据

数据展示

然后在Obsidian的日记模板
插入了下面代码段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<%*
let nowTime = tp.date.now("HH:mm")
let currenttime = moment(nowTime,"HH:mm");
if(currenttime.isBefore(moment("22:30","HH:mm"))){
console.log(`${nowTime} 在22:30之前`)%>
```meta-bind-button
label: 今日天气变化
icon: ""
hidden: false
class: ""
tooltip: "点击生成今日天气变化"
id: ""
style: default
actions:
- type: command
command: templater-obsidian:insert-templater
```
<%*}else{
console.log(`${nowTime} 在22:30之后`)
let currentTime = tp.date.now("YYYY-MM-DD")
let fileName = `${currentTime}.txt`
let result = await tp.user.todayWeather(fileName)
let timearr = `[${result[0]}]`
let temparr = `[${result[1]}]`
%>
```chart
type: line
labels: <% temparr %>
series:
- title: 温度
data: <% timearr %>
tension: 0.5
width: 100%
labelColors: false
fill: false
beginAtZero: true
bestFit: false
bestFitTitle: undefined
bestFitNumber: 0
```
<%*
}
-%>

添加了个插入今日天气变化的按钮
还有 图表插件chart 的代码段

创建日记时先获取当前的时间,然后和自己设定的时间进行对比
22:30之后就直接生成今天一天的气温变化
如果是22:30之前创建的日记,那么就会加载一个插入今天的天气的按钮(使用插件meta bind实现)
方便晚上写日记的时候添加.

最终结果

image-20240509142348928