File size: 3,834 Bytes
82a7fd2
 
 
 
 
c8c2db2
762f7b9
 
7f00a8d
 
 
 
82a7fd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8c2db2
82a7fd2
 
 
 
 
 
 
c8c2db2
6b95d04
762f7b9
 
641e286
 
88a09c6
 
762f7b9
c8c2db2
82a7fd2
762f7b9
 
 
82a7fd2
6b95d04
c8c2db2
 
82a7fd2
 
 
 
 
 
 
 
 
 
c8c2db2
82a7fd2
 
 
 
 
 
 
 
 
 
 
c8c2db2
 
 
762f7b9
 
 
 
7f00a8d
762f7b9
 
 
 
 
 
 
 
c8c2db2
 
 
7f00a8d
c8c2db2
 
 
 
 
 
82a7fd2
88a09c6
 
 
7f00a8d
 
 
 
 
 
 
 
 
88a09c6
c8c2db2
 
762f7b9
641e286
c8c2db2
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import streamlit as st
import pandas as pd
import numpy as np
import requests
import time
from datetime import datetime
from timeit import default_timer as timer
from datetime import timedelta
import matplotlib.pyplot as plt
# import warnings
# warnings.filterwarnings("ignore")
# import seaborn as sns

st.set_page_config(
    page_title="Real-Time IoT",
    page_icon="βœ…",
    layout="wide",
)

st.title("Iot Data")

DATA_URL = 'https://trace.vfsc.vn/iot/xxx'

# def stream():
#     s = requests.Session()
#     with requests.get(DATA_URL, headers=None, stream=True, params={"items":160}) as response:
#         # print(response.status_code)
#         for line in response.iter_lines():
#             if line: print(line)
#             #     print(line.decode('utf-8')['data'])

# stream()


def load_data(n):
    response = requests.get(DATA_URL) if n <= 0 else requests.get(DATA_URL, params = {"items": n})

    plan = response.json()['plan'] 
    data = response.json()['data']

    return data


def is_duplicate(s):
    # st.write(s)
    res = False
    if "duplicates" in st.session_state:
        check_candidate = (s["Id"], s["Time"])
        res = check_candidate in st.session_state["duplicates"]
    else:
        st.session_state["duplicates"] = set()
    st.session_state["duplicates"].add(check_candidate)
    return res

if 'time' not in st.session_state:
    st.session_state['time'] = timer()


df = pd.DataFrame.from_dict(load_data(10))
df.rename({'Lat' : 'lat', 'Lng' : 'lon'}, axis='columns', inplace=True)
st.session_state["duplicates"] = set(zip(df["Id"], df["Time"]))

col1, col2 = st.columns(2)

graph_type = "Bar"
data_col   = "STemp"


with col1:
    data_col = st.selectbox(
        "Choose column to plot",
        [col for col in df.columns if col.lower() in "upt, batv, solv, stemp".split(", ")],
    )

    # st.checkbox("Disable selectbox widget", key="disabled")
    graph_type = st.radio(
        "Choose graph type πŸ‘‰",
        ('Bar', 'Line'),
    )

with col2:
    placeholder = st.empty()
    while True:
        # new_df = pd.DataFrame.from_dict(load_data(st.session_state["count"]))
        # new_df.rename({'Lat' : 'lat', 'Lng' : 'lon'}, axis='columns', inplace=True)

        curr_time = timer()

        # st.write(timedelta(seconds = curr_time - st.session_state['time']))
        if curr_time - st.session_state['time'] >= 2:
            # st.write("Passed")
            new_data = pd.DataFrame.from_dict(load_data(0)).rename({'Lat' : 'lat', 'Lng' : 'lon'}, axis='columns').iloc[-1]
                # print(df.iloc[-1]["Id"], new_data["Id"])
            if is_duplicate(new_data):
                pass
                # st.write("Dup")
            else:
                df.loc[len(df)] = new_data
            st.session_state['time'] = curr_time

        # df = pd.concat([df, pd.DataFrame(new_ele)])

        chart_data = (
            df[data_col].tolist(),
            df["moment"].apply(lambda timestr : datetime.strptime(timestr, '%d/%m/%Y %H:%M:%S').time().strftime("%H:%M:%S")).tolist()
        )

        # chart_data.set_index('date')

        with placeholder.container():
            plt.rcParams["figure.figsize"] = (20, 8)
            plt.close()
            fig, ax = plt.subplots()
            try:
                if graph_type == 'Line':
                    ax.plot(range(len(chart_data[0])), chart_data[0])
                elif graph_type == 'Bar':
                    ax.bar(range(len(chart_data[0])), chart_data[0])
                plt.xticks(range(len(chart_data[0])), chart_data[1])
                # st.bar_chart(chart_data)
            except Exception as e:
                pass
            st.pyplot(fig)
            # st.map(df)
            st.write(df)
        # time.sleep(15)
        # st.write(st.session_state)
        # st.session_state["count"] += 1