104 lines
2.6 KiB
TypeScript
104 lines
2.6 KiB
TypeScript
import { PlatformConfig } from 'homebridge'
|
|
|
|
import { domoticaPlatform } from './platform'
|
|
|
|
const request = require("request")
|
|
const http = require('http')
|
|
const url = require('url')
|
|
|
|
export class httpServer {
|
|
private address
|
|
private port
|
|
|
|
constructor(
|
|
private readonly platform: domoticaPlatform,
|
|
private readonly config: PlatformConfig
|
|
) {
|
|
this.address = "0.0.0.0"
|
|
this.port = 8080
|
|
}
|
|
|
|
serverCallback (request, response) {
|
|
var urlObject = url.parse(request.url, true)
|
|
var urlQuery = urlObject.query
|
|
var body: Uint8Array[] = []
|
|
var log = this.platform.log
|
|
|
|
request.on('error', (err) => {
|
|
log.debug("[ERROR Homebridge Domotica HttpServer] Reason: %s.", err)
|
|
}).on('data', (chunk) => {
|
|
body.push(chunk)
|
|
}).on('end', () => {
|
|
var bodyString = Buffer.concat(body).toString()
|
|
|
|
response.on('error', function(err) {
|
|
log.debug("[ERROR Homebridge Domotica HttpServer] Reason: %s.", err)
|
|
})
|
|
|
|
response.statusCode = 200
|
|
response.setHeader('Content-Type', 'application/json')
|
|
|
|
if (!urlQuery.type || !urlQuery.typeId) {
|
|
response.statusCode = 404
|
|
response.setHeader("Content-Type", "text/plain")
|
|
var errorText = "[ERROR Homebridge Domotica HttpServer] Type or TypeId missing in request."
|
|
response.write(errorText)
|
|
response.end()
|
|
} else {
|
|
var type = urlQuery.type
|
|
var typeId = urlQuery.typeId
|
|
|
|
if (type != "PowerSocket" && type != "PowerSwitch" && type != "Xiaomi" && type != "Camera" && type != "Activity") {
|
|
log.debug(request.url)
|
|
}
|
|
|
|
if (type == "Xiaomi") {
|
|
type = urlQuery.model
|
|
if (type == "TemperatureHumiditySensor") {
|
|
type = "EnvironmentSensor"
|
|
}
|
|
}
|
|
|
|
if (type == "Toon") {
|
|
type = "Thermostat"
|
|
}
|
|
|
|
|
|
var foundAccessory
|
|
|
|
for (const accessory of this.platform.accessories) {
|
|
if (accessory.type == type && accessory.typeId == typeId) {
|
|
foundAccessory = accessory
|
|
break
|
|
}
|
|
}
|
|
|
|
if (foundAccessory) {
|
|
for (const key of Object.keys(urlQuery)) {
|
|
if (key != "type" && key != "typeId") {
|
|
foundAccessory.setValue(key, urlQuery[key])
|
|
}
|
|
}
|
|
|
|
var responseBody = { "success" : true };
|
|
|
|
response.write(JSON.stringify(responseBody))
|
|
response.end()
|
|
} else {
|
|
response.setHeader("Content-Type", "text/plain")
|
|
errorText = "[ERROR Homebridge Domotica HttpServer] " + type + " " + typeId + " not found."
|
|
if (type != "PowerSocket") {
|
|
log.debug(errorText + '(' + request.url + ')')
|
|
}
|
|
response.write(errorText)
|
|
response.end()
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
start() {
|
|
http.createServer(this.serverCallback.bind(this)).listen(this.port, this.address)
|
|
}
|
|
}
|