Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

Commit

Permalink
beta support for local execution
Browse files Browse the repository at this point in the history
  • Loading branch information
gytisgreitai committed Jan 8, 2020
1 parent ef996e7 commit 111fa26
Show file tree
Hide file tree
Showing 13 changed files with 139 additions and 3,193 deletions.
5 changes: 5 additions & 0 deletions core/api/api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { OpenhabItem } from "../model/openhab";

export const ApiParameters = {
fields: 'editable,groupNames,groupType,name,label,metadata,stateDescription,tags,type',
metadata: 'google,channel,synonyms,autoupdate'
}

export interface Api {
getAll: () => Promise<OpenhabItem[]>
get: (item: string) => Promise<OpenhabItem>
Expand Down
6 changes: 3 additions & 3 deletions core/sync/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ export function toGoogleDevice(item: OpenhabItem, allItems: OpenhabItem[]): Smar
name: item.label,
nicknames: [item.label, ...getSynonyms(item.metadata)]
},
// otherDeviceIds: [
// {deviceId: item.name}
// ],
otherDeviceIds: [
{ deviceId: item.name }
],
roomHint: config && config.roomHint,
willReportState: false,
customData: {
Expand Down
8 changes: 4 additions & 4 deletions local-discovery/localDiscovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export function localDiscovery(config: DiscoveryConfig) {

socket
.on('message', async (msg, info) => {
console.log('local discovery message', msg, info)
const resp = await handleDiscoveryRequest(config, msg, info);
if (resp) {
const responsePacket = cbor.encode(resp);
Expand All @@ -26,7 +25,6 @@ export function localDiscovery(config: DiscoveryConfig) {
console.error("failed to send ack:", error);
return;
}
console.log(`sent discovery response: `,resp, 'to:', info);
});
}
})
Expand All @@ -43,10 +41,12 @@ async function handleDiscoveryRequest(config: DiscoveryConfig, msg: Buffer, info
console.warn("received unknown payload:", msg, "from:", info);
return;
}
const parsedUrl = new URL(config.openhabUrl);
let port = parsedUrl.port || (parsedUrl.protocol === 'https:' ? 443 : 80)

return {
deviceId: 'openhab-local',
port: Number(new URL(config.openhabUrl).port),
deviceId: 'openhab-local-device-hub',
port: Number(port),
itemPath: config.openhabItemsPath,
} as LocalDiscoveryData
}
82 changes: 34 additions & 48 deletions local/app.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,51 @@
/// <reference types="@google/local-home-sdk" />

import App = smarthome.App;
import Constants = smarthome.Constants;
import DataFlow = smarthome.DataFlow;

import Execute = smarthome.Execute;
import Intents = smarthome.Intents;

import IntentFlow = smarthome.IntentFlow;
import HttpResponseData = smarthome.DataFlow.HttpResponseData;


import * as cbor from 'cbor';
import { LocalDiscoveryData } from '@openhab-google-home/local-discovery';
import { OpenhabItem, toGoogleDevice } from '@openhab-google-home/core';
import { toGoogleDevice, execute } from '@openhab-google-home/core';
import { LocalApiProxy } from './localApiProxy';


export async function execute(app: App, request: IntentFlow.CloudRequest<IntentFlow.ExecuteRequestPayload>) {
console.log('execute request', request);
return {};
let lastDiscoveryData: LocalDiscoveryData ; //hack? No way to get port in REACHABLE_DEVICES and EXEC;

export async function onExecute(app: App, request: IntentFlow.CloudRequest<IntentFlow.ExecuteRequestPayload>) {

const response = new Execute.Response.Builder().setRequestId(request.requestId);

for (const r of request.inputs) {
for (const c of r.payload.commands) {
const { devices, execution } = c;
for (const device of devices) {
for (const e of execution) {
try {
const api = new LocalApiProxy(app, request.requestId, {...lastDiscoveryData, deviceId: device.id});
const result = await execute(api, device, e);
response.setSuccessState(result.ids[0], result.states);
} catch(e) {
console.error(e);
}
}
}
}
}
return response.build()
}

export async function identify(request: IntentFlow.RequestInterface<IntentFlow.LocalIdentifiedDevice, {}>) {
console.debug('identify request', request);
const device = request.inputs[0].payload.device;
console.debug('identify device', device);

export async function onIdentify(request: IntentFlow.RequestInterface<IntentFlow.LocalIdentifiedDevice, {}>) {
const device = request.inputs[0].payload.device;
const udpScanData = Buffer.from(device.udpScanData.data, "hex");
console.debug("udpScanData:", udpScanData);

const discoveryData: LocalDiscoveryData = await cbor.decodeFirst(udpScanData);
console.debug("discoveryData:", discoveryData);

lastDiscoveryData = discoveryData;
const response: IntentFlow.IdentifyResponse = {
intent: Intents.IDENTIFY,
requestId: request.requestId,
Expand All @@ -40,40 +57,12 @@ export async function identify(request: IntentFlow.RequestInterface<IntentFlow.L
},
},
};
console.debug('seding identify response', response)
return response;
}

// https://github.com/NabuCasa/home-assistant-google-assistant-local-sdk
export async function reachableDevices (app: App, request: IntentFlow.ReachableDevicesRequest) {
console.debug('reachableDevices', request);
// // Reference to the local proxy device
// const proxyDevice = request.inputs[0].payload.device.proxyDevice;

// const udpScanData = Buffer.from(proxyDevice.udpScanData, "hex");
// console.debug("udpScanData:", udpScanData);

// const discoveryData: LocalDiscoveryData = await cbor.decodeFirst(udpScanData);
// console.debug("discoveryData:", discoveryData);

const command = new DataFlow.HttpRequestData();
command.method = Constants.HttpOperation.GET;
command.requestId = request.requestId;
command.deviceId = 'openhab-local', // proxyDevice.id;
command.isSecure = false;
command.port = 8089 // discoveryData.port;
command.path = '/rest/items?fields=editable,groupNames,groupType,name,label,metadata,stateDescription,tags,type&metadata=google,channel,synonyms,autoupdate' //discoveryData.itemPath;
command.dataType = "application/json";

const deviceManager = app.getDeviceManager();

const resp =await deviceManager.send(command) as HttpResponseData;
console.log(request.requestId, "Raw Response", resp);

const items = JSON.parse(resp.httpResponse.body as string) as OpenhabItem[];
console.log('Got response', items);

// { verificationId: "local-device-id-2" },
export async function onReachableDevices (app: App, request: IntentFlow.ReachableDevicesRequest) {
const api = new LocalApiProxy(app, request.requestId, lastDiscoveryData);
const items = await api.getAll();
const devices = items.map(item => {
if (!item.metadata || !item.metadata.google) {
return;
Expand All @@ -83,9 +72,6 @@ export async function reachableDevices (app: App, request: IntentFlow.ReachableD
})
.filter(i => !!i)
.map(({id}) => ({ id }))

console.log('reachableDevices', devices);
// Return a response
const response: IntentFlow.ReachableDevicesResponse = {
intent: Intents.REACHABLE_DEVICES,
requestId: request.requestId,
Expand Down
Loading

0 comments on commit 111fa26

Please sign in to comment.