Skip to content

Commit ae72976

Browse files
committed
logging cleanup, example skeleton for components
1 parent 070b28b commit ae72976

File tree

7 files changed

+175
-39
lines changed

7 files changed

+175
-39
lines changed

aqi/main.py

Lines changed: 18 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
import datetime
2-
import logging
3-
import sys
42
from typing import Dict, List
53

64
import treq
@@ -21,8 +19,6 @@
2119
API_KEY = "53295F0D-285C-4787-8336-4DA76A434E03"
2220

2321
ns = "LA4-DATA-AQI"
24-
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
25-
logger = logging.Logger(ns)
2622

2723
AQI_PREFIX = NAMESPACE_PREFIX + "aqi."
2824

@@ -44,7 +40,7 @@ def as_obs_request(self):
4440

4541
class AQIObservationRequestParams(BaseModel):
4642
zipCode: str = Field(alias="zip_code")
47-
format: str = "application/json" #
43+
format: str = "application/json" #
4844
distance: int = 25
4945
API_KEY: str = Field(alias="api_key")
5046

@@ -53,7 +49,7 @@ class AQIForecastRequestParams(BaseModel):
5349
date: datetime.date
5450

5551
zipCode: str = Field(alias="zip_code")
56-
format: str = "application/json" #
52+
format: str = "application/json" #
5753
distance: int = 25
5854
API_KEY: str = Field(alias="api_key")
5955

@@ -104,18 +100,16 @@ class AQISession(LAMachineCompatMixin, ApplicationSession):
104100

105101
@inlineCallbacks
106102
def onJoin(self, details):
107-
logger.info("session ready")
108-
print("session ready")
103+
self.log.info("session ready")
109104
self.regs = yield self.register(self)
110105
self.subs = yield self.subscribe(self)
111106

112107
self.ticker_aqi = LoopingCall(self.ticker_update_aqi)
113108
self.ticker_aqi.start(1800) # 30m
114109

115110
self.herald_aqi = LoopingCall(self.aqi_herald)
116-
self.herald_aqi.start(10)
117-
print("completed startup")
118-
logger.info("completed startup")
111+
self.herald_aqi.start(.05)
112+
self.log.info("completed startup")
119113

120114
@wamp.register(AQI_PREFIX + "register")
121115
def register_config(self):
@@ -134,35 +128,39 @@ def aqi_herald(self):
134128
for res in res_list:
135129
id = f"{self.cconfig.machine_name.lower()}-{key}-{str(res.param_name).lower()}"
136130
yield self.publish(f"{SRC_PREFIX}{id}",
137-
self.run_brightness_on_val(observation_color_map[res.category.number] * LEDS_IN_ARRAY_DEFAULT),
138-
id=id, options=options)
131+
self.run_brightness_on_val(
132+
observation_color_map[res.category.number] * LEDS_IN_ARRAY_DEFAULT),
133+
id=id, options=options)
139134
if not self.aqi_results:
140-
print("Herald: No data has been loaded, chilling")
135+
self.log.info("Herald: No data has been loaded, chilling")
141136

142137
@inlineCallbacks
143138
def do_update_aqi(self, config_id: str):
144139
try:
145-
logger.info(f"Updating {config_id}")
146140
config = self.aqi_configs[config_id]
147141

148142
result = yield treq.get(self.PATH_OBSERVATIONS, params=config.as_obs_request().dict())
149143
data = yield result.json()
150144
# pls forgive the fucking federal govt
151145
for i in data:
152-
i['DateObserved'] = i['DateObserved'].replace(" ","")
146+
i['DateObserved'] = i['DateObserved'].replace(" ", "")
153147
self.aqi_results[config_id] = [AirNowObservation(**i) for i in data]
154148
except Exception as e:
155149
import traceback
156-
print(e)
157-
print(traceback.format_exc())
150+
self.log.error(e)
151+
self.log.error(traceback.format_exc())
158152

159153
def ticker_update_aqi(self):
160154
uninstantiated_results = set(self.aqi_configs.keys()) - set(self.aqi_results.keys())
155+
other_results = set(self.aqi_configs.keys()) - uninstantiated_results
161156
for ur in uninstantiated_results:
157+
self.log.info(f"Updating {ur} (1st)")
162158
self.do_update_aqi(ur)
163159

164-
for k in self.aqi_configs.keys():
165-
self.do_update_aqi(ur)
160+
for k in other_results:
161+
self.log.info(f"Updating {ur}")
162+
self.do_update_aqi(k)
163+
166164

167165
comp = Component(
168166
transports=u"ws://localhost:8083/ws",

compat.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
11
import dataclasses
22
import json
33
import logging
4+
from dataclasses import dataclass
45
from enum import Enum
56
from typing import Dict, Any, Optional
67

78
from autobahn import wamp
8-
from dataclasses import dataclass
9-
109
from autobahn.wamp import RegisterOptions
1110
from pydantic import BaseModel
1211
from pydantic.json import pydantic_encoder
@@ -134,7 +133,7 @@ def __init__(self, config=None):
134133
super().__init__(config)
135134

136135
self.brightness_ticker = LoopingCall(self.ticker_brightness_ctrl)
137-
self.brightness_ticker.start(.1) # 30m
136+
self.brightness_ticker.start(.1)
138137

139138
def ticker_brightness_ctrl(self):
140139
if self.brightness_act != self.brightness_tgt.value:

example.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
from dataclasses import dataclass
2+
from typing import Dict, Union, List
3+
4+
from autobahn import wamp
5+
from autobahn.twisted import ApplicationSession
6+
from autobahn.twisted.component import Component
7+
from autobahn.twisted.component import run
8+
from twisted.internet.defer import inlineCallbacks
9+
from twisted.internet.task import LoopingCall
10+
11+
from compat import LAMachineCompatMixin, CompatConfig
12+
from config import NAMESPACE_PREFIX
13+
14+
# Some declarations, change these
15+
16+
ns = "LA4-DATA-EXAMPLE"
17+
EXAMPLE_PREFIX = NAMESPACE_PREFIX + "example."
18+
19+
20+
@dataclass
21+
class SomeConfig:
22+
pass
23+
24+
25+
@dataclass
26+
class SomeResult:
27+
pass
28+
29+
30+
class ExampleSessionTwisted(LAMachineCompatMixin, ApplicationSession):
31+
cconfig = CompatConfig(
32+
machine_name=ns,
33+
desc_blurb="An Example Description for the UI"
34+
)
35+
36+
configs: Dict[str, SomeConfig] = {}
37+
results: Union[Dict[str, SomeResult], Dict[str, List[SomeResult]]] = {}
38+
39+
@wamp.register(EXAMPLE_PREFIX + "register")
40+
def register_config(self):
41+
pass
42+
43+
@wamp.register(EXAMPLE_PREFIX + "register")
44+
def remove_config(self):
45+
pass
46+
47+
def update_data(self):
48+
raise NotImplementedError("Need to configure a data update")
49+
50+
def herald_data(self):
51+
raise NotImplementedError("Need to configure a data herald")
52+
53+
@inlineCallbacks
54+
def onJoin(self, details):
55+
self.log.info("session ready")
56+
self.regs = yield self.register(self)
57+
self.subs = yield self.subscribe(self)
58+
59+
self.ticker_ex = LoopingCall(self.update_data)
60+
self.ticker_ex.start(1800) # 30m
61+
62+
self.herald_ex = LoopingCall(self.herald_data)
63+
self.herald_exs.start(10)
64+
65+
66+
comp = Component(
67+
transports=u"ws://localhost:8083/ws",
68+
realm=u"realm1",
69+
session_factory=ExampleSessionTwisted
70+
)
71+
if __name__ == "__main__":
72+
run([comp], log_level="info")

gbfs/__init__.py

Whitespace-only changes.

gbfs/main.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
from dataclasses import dataclass
2+
from typing import Dict, Union, List
3+
4+
from autobahn import wamp
5+
from autobahn.twisted import ApplicationSession
6+
from autobahn.twisted.component import Component
7+
from autobahn.twisted.component import run
8+
from twisted.internet.defer import inlineCallbacks
9+
from twisted.internet.task import LoopingCall
10+
11+
from compat import LAMachineCompatMixin, CompatConfig
12+
from config import NAMESPACE_PREFIX
13+
14+
ns = "LA4-DATA-GBFS"
15+
GBFS_PREFIX = NAMESPACE_PREFIX + "gbfs."
16+
17+
18+
@dataclass
19+
class SomeConfig:
20+
pass
21+
22+
23+
@dataclass
24+
class SomeResult:
25+
pass
26+
27+
28+
class GBFSSession(LAMachineCompatMixin, ApplicationSession):
29+
cconfig = CompatConfig(
30+
machine_name=ns,
31+
desc_blurb="A GBFS Provider"
32+
)
33+
34+
configs: Dict[str, SomeConfig] = {}
35+
results: Union[Dict[str, SomeResult], Dict[str, List[SomeResult]]] = {}
36+
37+
@wamp.register(GBFS_PREFIX + "register")
38+
def register_config(self):
39+
pass
40+
41+
@wamp.register(GBFS_PREFIX + "register")
42+
def remove_config(self):
43+
pass
44+
45+
def update_data(self):
46+
raise NotImplementedError("Need to configure a data update")
47+
48+
def herald_data(self):
49+
raise NotImplementedError("Need to configure a data herald")
50+
51+
@inlineCallbacks
52+
def onJoin(self, details):
53+
self.log.info("session ready")
54+
self.regs = yield self.register(self)
55+
self.subs = yield self.subscribe(self)
56+
57+
self.ticker_ex = LoopingCall(self.update_data)
58+
self.ticker_ex.start(1800) # 30m
59+
60+
self.herald_ex = LoopingCall(self.herald_data)
61+
self.herald_exs.start(10)
62+
63+
64+
comp = Component(
65+
transports=u"ws://localhost:8083/ws",
66+
realm=u"realm1",
67+
session_factory=GBFSSession
68+
)
69+
if __name__ == "__main__":
70+
run([comp], log_level="info")

gbfs/models.py

Whitespace-only changes.

gtfs/main.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
import csv
22
import datetime
3-
import logging
43
import os
5-
import treq
64
import zipfile
75
from dataclasses import dataclass, field
86
from typing import List, Dict, Optional, Any
97

108
import pytz
9+
import treq
1110
from aenum import Enum
1211
from autobahn import wamp
1312
from autobahn.twisted import ApplicationSession
@@ -22,7 +21,6 @@
2221

2322
GTFS_PREFIX = NAMESPACE_PREFIX + "gtfs."
2423
ns = "LA4-DATA-GTFS"
25-
logger = logging.Logger(ns)
2624

2725

2826
class GTFSParsers(Enum):
@@ -106,12 +104,11 @@ def get_next_schedules_for_stop(self, id: str, tz: str = "America/New_York", min
106104

107105
stop_times = self._get_stop_times_by_id(id)
108106
nearby_times = self._filter_to_find_closest_times(stop_times, now, fut)
109-
print(nearby_times)
110107
trips = self._get_trips_by_id([i.trip_id for i in nearby_times])
111-
print(trips)
112-
print("Upcoming")
108+
self.log.info("Upcoming")
113109
for t in sorted(nearby_times, key=lambda x:x.arrival_time):
114-
print(f"Line {trips[t.trip_id].route_id} Arrives at {t.arrival_time} {t.arrival_time_as_delta_seconds(now)} ")
110+
self.log.info(
111+
f"Line {trips[t.trip_id].route_id} Arrives at {t.arrival_time} {t.arrival_time_as_delta_seconds(now)} ")
115112

116113

117114

@@ -142,7 +139,7 @@ class GTFSSession(ApplicationSession):
142139

143140
@inlineCallbacks
144141
def onJoin(self, details):
145-
print("session ready")
142+
self.log.info("session ready")
146143
self.regs = yield self.register(self)
147144
self.subs = yield self.subscribe(self)
148145

@@ -203,7 +200,7 @@ def parse_bundle(self, config_id: str):
203200
for file in os.listdir(f"cache/{config_id}/bundle"):
204201
file_pre = file.replace('.txt', '')
205202
if file_pre not in [i.name for i in GTFSParsers]:
206-
print(f"{file_pre} was not found in our parser list, may be a gtfs+/experimental entity")
203+
self.log.info(f"{file_pre} was not found in our parser list, may be a gtfs+/experimental entity")
207204
continue
208205
kwargs[file_pre] = []
209206
with open(f"cache/{config_id}/bundle/{file}", 'r') as file_handle:
@@ -213,14 +210,14 @@ def parse_bundle(self, config_id: str):
213210
kwargs[file_pre].append(getattr(GTFSParsers, file_pre).value(**dict(zip(header, row))))
214211

215212
self.gtfs_results[config_id] = GTFSResults(**kwargs)
216-
print("Completed Ingesting")
213+
self.log.info(f"Completed Ingesting {config_id}")
217214

218215
except Exception as e:
219-
print(e)
216+
self.log.error(e)
220217

221218
@inlineCallbacks
222219
def do_update(self, config_id: str):
223-
logger.info(f"Updating {config_id}")
220+
self.log.info(f"Updating {config_id}")
224221
self.assert_directory_structure(config_id)
225222
yield self.download_and_write(config_id)
226223
self.unzip_bundle(config_id)
@@ -242,14 +239,14 @@ def gtfs_herald(self):
242239
for i in self.gtfs_results:
243240
config = self.gtfs_configs[i]
244241
for stop in config.relevant_stops:
245-
print(f"heralding {i} - {stop}")
242+
self.log.debug(f"heralding {i} - {stop}")
246243
self.gtfs_results[i].get_next_schedules_for_stop(stop)
247244
if not self.gtfs_results:
248-
print("Herald: No data has been loaded, chilling")
245+
self.log.info("Herald: No data has been loaded, chilling")
249246
except Exception as e:
250247
import traceback
251-
print(e)
252-
print(traceback.format_exc())
248+
self.log.error(e)
249+
self.log.error(traceback.format_exc())
253250

254251
comp = Component(
255252
transports=u"ws://localhost:8083/ws",

0 commit comments

Comments
 (0)