Так что я tryna запускаю скрипт python, который считывает данные с датчиков Z-волны через Rpi и использует crontab на pi, который я установил, чтобы скрипт python запускался каждую минуту и хранилище это в текстовом файле. Затем у меня есть еще один скрипт python, который отправляет данные в облачное хранилище azure в виде таблицы. Проблема в том, что это создание таблицы, но theres ошибка «Этот XML-файл, похоже, не связан с ним информацией о стиле, связанной с ней». Я пытался понять это, но я ничего не вижу, это неправильно.скрипты python для создания таблицы на azure
Это питон скрипт, который отправляет данные в облако
from azure.storage import TableService, Entity
from datetime import datetime
import socket
ac_name = 'account name'
#you will have to use your own azure account
primary_key = 'use your key'
table_name = 'Readings'
current_temperature = 0
def get_connection_string_and_create_table():
global table_service
table_service = TableService(account_name = ac_name,account_key=primary_key)
#table_service.delete_table(table_name = table_name) #TO BE USED IF THE TABLE NEEDS TO BE DELETED
table_service.create_table(table=table_name)
def insert_data():
reading = create_entity()
try:
if check_internet_available():
table_service.insert_entity(table_name = table_name,entity = reading)
return True
except Exception, e:
return False
def create_entity():
"""
- Creates the data block that would be sent to the cloud, named as Entity
"""
time_now = datetime.strftime(datetime.now(),'%d-%m-%Y %H:%M:%S')
print('Date time is {0}'.format(time_now))
reading = Entity()
reading.PartitionKey = 'Room1'
reading.RowKey = time_now
reading.Timestamp = datetime.now()
reading.Temperature = str(current_temperature)
return reading
def initialize_azure():
get_connection_string_and_create_table()
def send_data_to_cloud(temperature):
global current_temperature
current_temperature = temperature
sent_success = insert_data()
print temperature
print sent_success
return sent_success
def check_internet_available():
"""
- Checks internet availability, the data will be sent to cloud
only if there is an active internet connection
remote_server = 'www.google.com'
try:
host = socket.gethostbyname(remote_server)
s = socket.create_connection((host,80),2)
return True
except:
pass
return False
if __name__ == '__main__':
get_connection_string_and_create_table()
f = open('Meter.txt', 'r')
send_data_to_cloud(f.readline())
И это скрипт, который считывает данные через HTTP запросов от API
import urllib2
import json
import requests
import time
import json
class EnergyConsumptionControl:
# Class constructor
def __init__(self):
# Global Variables
self.energyMeterDeviceUrl = "http://IpaddressofyourRpi"
self.session = requests.Session()
# Logging in
self.Login()
def ActivateDevice(self, deviceID):
energyMeterDeviceSwitchOn = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].SwitchBinary.Set(255)"
response = self.SendGetCommand(energyMeterDeviceSwitchOn) # Command to turn device on
return [response]
def DeactivateDevice(self, deviceID):
energyMeterDeviceSwitchOff = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].SwitchBinary.Set(0)"
response = self.SendGetCommand(energyMeterDeviceSwitchOff) # Command to turn device off
return [response]
def GetDeviceState(self, deviceID):
# Call the Get() function to update the SwitchBinary data
energyMeterDeviceSwitchGet = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].SwitchBinary.Get()"
response = self.SendGetCommand(energyMeterDeviceSwitchGet)
# Call to return the SwitchBinary JSON object
energyMeterDeviceSwitchGet = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].SwitchBinary"
response = self.SendGetDeviceStateCommand(energyMeterDeviceSwitchGet)
return response
# def GetDeviceMeter(self, deviceID):
# # Refreshing server-side information on the Meter through device interrogation
# energyMeterDeviceMeterGetVals = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].Meter.Get()"
# response = self.SendGetCommand(energyMeterDeviceMeterGetVals)
# # Retrieving the JSON of all Meter related data
# energyMeterDeviceMeterGet = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].Meter"
# response = self.GetMeterWattage(energyMeterDeviceMeterGet)
# return [response]
def GetDeviceEnergyConsumption(self, deviceID):
# Refreshing server-side information on the Meter through device interrogation
energyMeterDeviceMeterRefreshVals = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].Meter"
response = self.SendGetCommand(energyMeterDeviceMeterRefreshVals)
# Retrieving the JSON of all Meter related data
energyMeterDeviceMeterGetVals = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].Meter"
energyConsumption = self.GetMeterConsumption(energyMeterDeviceMeterGetVals)
response = self.ResetDeviceMeter(deviceID)
return energyConsumption
def GetDeviceEnergyWattage(self, deviceID):
# Refreshing server-side information on the Meter through device interrogation
energyMeterDeviceMeterRefreshVals = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].Meter.Get()"
response = self.SendGetCommand(energyMeterDeviceMeterRefreshVals)
# Retrieving the JSON of all Meter related data
energyMeterDeviceMeterGetVals = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].Meter"
energyWattage = self.GetMeterWattage(energyMeterDeviceMeterGetVals)
print energyWattage
return energyWattage
def ResetDeviceMeter(self, deviceID):
energyMeterDeviceMeterReset = ":8083/ZWaveAPI/Run/devices[" + str(deviceID) + "].Meter.Reset(255)"
response = self.SendPostCommand(energyMeterDeviceMeterReset) # Command to reset device meter value
return [response]
def Login(self):
data = {
"form": True,
"login": "admin",
"password": "#password",
"keepme": False,
"default_ui": 1
}
# Authenticating
headers = {'Content-Type': 'application/json'}
response = self.session.post(self.energyMeterDeviceUrl + ':8083/ZAutomation/api/v1/login', headers=headers,
data=json.dumps(data))
# Generic function to send GET commands to individual Z-Wave devices
def SendGetCommand(self, command):
status = self.session.get(self.energyMeterDeviceUrl + command)
print status
print status.text
return [status]
# Generic function to send POST commands to individual Z-Wave devices
def SendPostCommand(self, command):
status = self.session.post(self.energyMeterDeviceUrl + command)
print status
print status.text
return [status]
def GetMeterWattage(self, command):
status = self.session.get(self.energyMeterDeviceUrl + command)
json_data = json.loads(status.text)
# Parsing the JSON data to get just the energy wattage (W)
return json_data['data']['2']['val']['value']
def GetMeterConsumption(self, command):
status = self.session.get(self.energyMeterDeviceUrl + command)
json_data = json.loads(status.text)
# Parsing the JSON data to get just the energy consumption (kWh)
return json_data['data']['0']['val']['value']
def SendGetDeviceStateCommand(self, command):
status = self.session.get(self.energyMeterDeviceUrl + command)
json_data = json.loads(status.text)
# Parsing the JSON data to get just the 'level'
return int(json_data['data']['level']['value'])
control = EnergyConsumptionControl()
response = control.GetDeviceEnergyConsumption(8)
print response
control = EnergyConsumptionControl()
response = control.ActivateDevice(8)
print response
Есть ли способ, чтобы либо объединить два, чтобы он вызывал данные и отправлял их в облако? Как исправить ошибку Сообщение
Вы можете проверить свой код отдельно, чтобы найти, где проблема, загрузки кода или загрузки кода. Вы облака видите содержимое загружаемого файла, чтобы проверить, является ли он стандартным XML-файлом. Этот URL-адрес http://stackoverflow.com/questions/14804452/opening-facelets-page-errors-with-this-xml-file-does-not-appear-to-have-any-sty может оказаться полезным. – johnny