-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlambda_function.py
239 lines (199 loc) · 8.08 KB
/
lambda_function.py
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import asyncio
import os
import logging
from typing import Dict
from urllib.parse import parse_qs
import json
import boto3
import copy
import urllib.request
from dataclasses import dataclass, asdict
from lmcloud.client_cloud import LaMarzoccoCloudClient
from lmcloud.lm_machine import LaMarzoccoMachine
from lmcloud.const import MachineModel, BoilerType
from lmcloud.exceptions import AuthFail, RequestNotSuccessful
from lmcloud.models import LaMarzoccoMachineConfig
USERNAME = os.environ["USERNAME"]
PASSWORD = os.environ["PASSWORD"]
SERIAL_NUMBER = os.environ["SERIAL_NUMBER"]
NAME = os.environ["NAME"]
DEBUG = os.environ.get("DEBUG", False)
logger = logging.getLogger()
if DEBUG:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
class LaMarzoccoLambdaError(Exception):
pass
@dataclass
class Response:
statusCode: int
body: str
def __init__(self, statusCode: int, body: Dict):
self.statusCode = statusCode
self.body = json.dumps(body)
def to_dict(self):
return asdict(self)
@dataclass
class LaMarzoccoMachineWrapper:
name: str
serial_number: str
model: str
def to_dict(self):
return asdict(self)
@dataclass
class LaMarzoccoMachineStatus:
turned_on: bool
steam_boiler_on: bool
steam_boiler_temp: int
steam_boiler_target_temp: int
main_boiler_on: bool
main_boiler_temp: int
main_boiler_target_temp: int
@staticmethod
def from_la_marzocco_machine_config(
config: LaMarzoccoMachineConfig,
) -> "LaMarzoccoMachineStatus":
steam_boiler = config.boilers[BoilerType.STEAM]
main_boiler = config.boilers[BoilerType.COFFEE]
return LaMarzoccoMachineStatus(
turned_on=config.turned_on,
steam_boiler_on=steam_boiler.enabled,
steam_boiler_temp=steam_boiler.current_temperature,
steam_boiler_target_temp=steam_boiler.target_temperature,
main_boiler_on=main_boiler.enabled,
main_boiler_temp=main_boiler.current_temperature,
main_boiler_target_temp=main_boiler.target_temperature,
)
def to_dict(self):
return asdict(self)
async def login() -> LaMarzoccoCloudClient:
logger.info("creating LaMarzoccoCloudClient object")
cloud_client = LaMarzoccoCloudClient(USERNAME, PASSWORD)
return cloud_client
async def get_machine(cloud_client: LaMarzoccoCloudClient) -> LaMarzoccoMachine:
try:
logger.info("getting machine...")
machine = await LaMarzoccoMachine.create(
MachineModel.LINEA_MICRA, SERIAL_NUMBER, NAME, cloud_client
)
logger.info("got machine successfully")
except AuthFail as e:
logger.error(f"failed to login to La Marzocco Cloud: {e}")
raise LaMarzoccoLambdaError("failed to login to La Marzocco Cloud")
except RequestNotSuccessful as e:
logger.error(f"failed to get machine: {e}")
raise LaMarzoccoLambdaError("failed to get machine")
return machine
async def list_machines(
cloud_client: LaMarzoccoCloudClient,
) -> Dict[str, LaMarzoccoMachineWrapper]:
machines: Dict[str, LaMarzoccoMachineWrapper] = {}
try:
logger.info("getting customer fleet...")
fleet = await cloud_client.get_customer_fleet()
logger.info("got customer fleet successfully")
except AuthFail as e:
logger.error(f"failed to login to La Marzocco Cloud: {e}")
raise LaMarzoccoLambdaError("failed to login to La Marzocco Cloud")
except RequestNotSuccessful as e:
logger.error(f"failed to get customer fleet: {e}")
raise LaMarzoccoLambdaError("failed to get customer fleet")
for machine_name, lmdi in fleet.items():
wrapper = LaMarzoccoMachineWrapper(machine_name, lmdi.serial_number, lmdi.model)
machines[machine_name] = wrapper
return machines
def parse_event(event: Dict) -> Dict:
logger.info(str(event))
content_type = event.get("headers", {}).get(
"content-type", "application/x-www-form-urlencoded"
)
logger.debug(f"Got event with Content-Type {content_type}")
match content_type.lower():
case "application/json":
if "body" in event:
return json.loads(event["body"])
raise LaMarzoccoLambdaError("Invalid event: " + str(event))
case "application/x-www-form-urlencoded":
parsed_data = parse_qs(event["body"])
return {k: v[0] for k, v in parsed_data.items()}
case _:
raise LaMarzoccoLambdaError(f"Unsupported Content-Type: {content_type}")
async def turn_on() -> Response:
cloud_client = await login()
logger.info("Logged in")
machine = await get_machine(cloud_client)
logger.info("Got machine")
try:
if not await machine.set_power(True):
logger.info("Set power failed")
return Response(401, {"message": "failed to turn on machine"})
logger.info("Set power success")
return Response(200, {})
except RequestNotSuccessful as e:
return Response(400, {"message": "failed to turn on machine", "e": str(e)})
async def async_slack_handler(event, parsed_event, context, is_background) -> Response:
if ["/tired"] == parsed_event["command"] or "/tired" == parsed_event["command"]:
if is_background:
t = await turn_on()
response_message = {
"text": "The machine has been turned on."
}
data = json.dumps(response_message).encode('utf-8')
req = urllib.request.Request(parsed_event['response_url'],
data=data,
headers={'Content-Type': 'application/json'})
urllib.request.urlopen(req)
return t
else:
# Invoke the background processing asynchronously
lambda_client = boto3.client("lambda")
lambda_client.invoke(
FunctionName=context.function_name,
InvocationType="Event", # Asynchronous invocation
Payload=json.dumps({"background": True, **event}),
)
return Response(202, 'Hmm... wait a sec!')
raise ValueError(f"IDK what to do, {event}")
async def async_handler(event, context) -> Response:
is_background = "background" in event
original_event = copy.copy(event)
event = parse_event(event)
if "action" not in event:
return await async_slack_handler(original_event, event, context, is_background)
logger.info(f'Got action: {event["action"]}')
try:
match event["action"]:
case "list_machines":
cloud_client = await login()
machines = await list_machines(cloud_client)
return Response(200, machines)
case "turn_on":
return await turn_on()
case "turn_off":
cloud_client = await login()
machine = await get_machine(cloud_client)
try:
if not await machine.set_power(False):
return Response(400, {"message": "failed to turn off machine"})
return Response(200, {})
except RequestNotSuccessful as e:
return Response(
400, {"message": "failed to turn off machine", "e": str(e)}
)
case "get_status":
cloud_client = await login()
machine = await get_machine(cloud_client)
config = machine.config
status = LaMarzoccoMachineStatus.from_la_marzocco_machine_config(config)
return Response(200, status.to_dict())
case _:
return Response(400, {"message": f"unknown action {event['action']}"})
except RequestNotSuccessful as e:
return Response(400, {"message": "request not successful", "e": str(e)})
except LaMarzoccoLambdaError as e:
return Response(400, {"message": str(e)})
def handler(event, context):
logger.debug(f"event: {event}")
response = asyncio.run(async_handler(event, context))
return response.to_dict()