void write(std::string time, ILogger::Level level, std::string message)
{
std::cout << "[APPLogger] " << time << " " << ILogger::getString(level) << " "
- << message;
+ << message;
}
};
std::shared_ptr<AppLogger> gAppLogger(new AppLogger());
class SimLightResource
{
public:
- void startTest(std::string &configPath)
+ void startTest()
{
printMenu();
bool cont = true;
switch (choice)
{
- case 1 : simulateResource(configPath); break;
+ case 1 : simulateResource(); break;
case 2 : displayResource(); break;
- case 3 :
- try
- {
- deleteResource();
- }
- catch (InvalidArgsException &e)
- {
- std::cout << "InvalidArgsException occured [code : " << e.code() <<
- " Detail: " << e.what() << "]" << std::endl;
- }
- break;
+ case 3 : deleteResource(); break;
case 4 : updateAttributePower(); break;
case 5 : updateAttributeIntensity(); break;
case 6 : automateResourceUpdate(); break;
const SimulatorResourceModel &resModel)
{
std::cout << "[callback] Resource model is changed URI: " << uri.c_str()
- << " Count : " << resModel.size() << std::endl;
+ << " Count : " << resModel.size() << std::endl;
std::cout << "#### Modified attributes are ####" << std::endl;
for (auto & attribute : resModel.getAttributes())
{
std::cout << attribute.second.getName() << " : "
- << attribute.second.valueToString().c_str() << std::endl;
+ << attribute.second.valueToString().c_str() << std::endl;
}
std::cout << "########################" << std::endl;
}
- void simulateResource(std::string &configPath)
+ void simulateResource()
{
SimulatorResourceServer::ResourceModelChangedCB callback = std::bind(
&SimLightResource::onResourceModelChanged, this, std::placeholders::_1,
try
{
+ std::string configPath;
+ std::cout << "Enter RAML path: ";
+ std::cin>>configPath;
SimulatorResourceServerSP resource =
- SimulatorManager::getInstance()->createResource(configPath, callback);
+ SimulatorManager::getInstance()->createResource(configPath, callback);
m_resources.push_back(resource);
std::cout << "Resource created successfully! URI= " << resource->getURI().c_str()
- << std::endl;
+ << std::endl;
}
catch (InvalidArgsException &e)
{
std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
- << e.what() << "]" << std::endl;
+ << e.what() << "]" << std::endl;
}
catch (SimulatorException &e)
{
std::cout << "SimulatorException occured [code : " << e.code() << " Detail: "
- << e.what() << "]" << std::endl;
+ << e.what() << "]" << std::endl;
}
}
{
SimulatorManager::getInstance()->deleteResource(resourceType);
std::cout << "Resources of type \"" << resourceType << "\"" <<
- " deleted successfully! " << std::endl;
+ " deleted successfully! " << std::endl;
std::vector<SimulatorResourceServerSP>::iterator ite = m_resources.begin();
while (ite != m_resources.end())
{
catch (InvalidArgsException &e)
{
std::cout << "InvalidArgsException occured [code : " << e.code()
- << " Detail: " << e.what() << "]" << std::endl;
+ << " Detail: " << e.what() << "]" << std::endl;
}
catch (SimulatorException &e)
{
std::cout << "SimulatorException occured [code : " << e.code()
- << " Detail: " << e.what() << "]" << std::endl;
+ << " Detail: " << e.what() << "]" << std::endl;
}
} break;
}
std::cout << "Setting the new values from allowed values list to power attribute" <<
- std::endl;
+ std::endl;
// Update all possible values from allowed values
for (int index = 0; index < allowedValuesSize; index++)
{
}
std::cout << "Setting the new values from allowed values list to intensity attribute"
- << std::endl;
+ << std::endl;
// Update all possible values from allowed values
for (int index = min; index <= max; index++)
{
// Attributes
SimulatorResourceModel resModel = resource->getModel();
std::map<std::string, SimulatorResourceModel::Attribute> attributes =
- resModel.getAttributes();
+ resModel.getAttributes();
std::cout << "##### Attributes [" << attributes.size() << "]" << std::endl;
for (auto & attribute : attributes)
{
const int id)
{
std::cout << "Update automation is completed [URI: " << uri.c_str()
- << " AutomationID: " << id << "] ###" << std::endl;
+ << " AutomationID: " << id << "] ###" << std::endl;
}
void automateResourceUpdate()
try
{
- int id = m_resources[index - 1]->startUpdateAutomation(type,
+ int id = m_resources[index - 1]->startUpdateAutomation(type, 500,
std::bind(&SimLightResource::onUpdateAutomationCompleted, this,
- std::placeholders::_1, std::placeholders::_2));
+ std::placeholders::_1, std::placeholders::_2));
std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
}
catch (SimulatorException &e)
{
std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
- e.what() << "]" << std::endl;
+ e.what() << "]" << std::endl;
}
}
SimulatorResourceServerSP resource = m_resources[index - 1];
SimulatorResourceModel resModel = resource->getModel();
std::map<std::string, SimulatorResourceModel::Attribute> attributes =
- resModel.getAttributes();
+ resModel.getAttributes();
int size = 0;
for (auto & attribute : attributes)
{
int choice = -1;
std::cout << "Select the attribute which you want to automate for updation: " <<
- std::endl;
+ std::endl;
std::cin >> choice;
if (choice < 0 || choice > size)
{
type = AutomationType::RECURRENT;
std::cout << "Requesting attribute automation for " << attributeName.c_str() <<
- std::endl;
+ std::endl;
try
{
- int id = resource->startUpdateAutomation(attributeName, type,
+ int id = resource->startUpdateAutomation(attributeName, type, 500,
std::bind(&SimLightResource::onUpdateAutomationCompleted, this,
- std::placeholders::_1, std::placeholders::_2));
+ std::placeholders::_1, std::placeholders::_2));
std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
}
catch (SimulatorException &e)
{
std::cout << "SimulatorException occured [Error: " << e.code() << " Details: " <<
- e.what() << "]" << std::endl;
+ e.what() << "]" << std::endl;
}
}
if (!ids.size())
{
std::cout << "No automation operation is going on this resource right now!" <<
- std::endl;
+ std::endl;
return;
}
std::ostringstream out;
out << "ID: " << (int) observerInfo.id << std::endl;
out << " [address: " << observerInfo.address << " port: " << observerInfo.port
- << "]" << std::endl;
+ << "]" << std::endl;
std::cout << out.str();
}
for (auto & observerInfo : observersList)
{
std::cout << " ID : " << (int) observerInfo.id << " [address: " <<
- observerInfo.address << " port: " << observerInfo.port << "]" << std::endl;
+ observerInfo.address << " port: " << observerInfo.port << "]" << std::endl;
}
std::cout << "########################" << std::endl;
}
std::cout << "2. Set Logger" << std::endl;
std::cout << "3. Help" << std::endl;
std::cout << "0. Exit" << std::endl;
- std::cout <<
- "To set the Resource from RAML file, run the service provider with argument of Path of Raml File."
- << std::endl;
- std::cout <<
- "Example: ./simulator-server PATH-TO-RAML-FILE"
- << std::endl;
std::cout << "######################################" << std::endl;
}
int main(int argc, char *argv[])
{
- std::string configPath = "";
-
- if (argc == 2)
- {
- char *value = argv[1];
- configPath.append(value);
- }
- else
- {
- configPath = "";
- }
SimLightResource lightResource;
printMainMenu();
switch (choice)
{
- case 1: lightResource.startTest(configPath);
+ case 1: lightResource.startTest();
std::cout << "Welcome back to main menu !" << std::endl;
break;
case 2: setLogger(); break;
bool compare(Attribute &attribute);
- std::vector<ValueVariant> getAllowedValues();
+ std::vector<ValueVariant> getAllowedValues() const;
int getUpdateFrequencyTime() {return m_updateInterval;}
void setUpdateFrequencyTime(int interval) {m_updateInterval = interval;}
ValueVariant &at(unsigned int index);
int size() const;
std::vector<std::string> toString() const;
- std::vector<ValueVariant> getValues();
+ std::vector<ValueVariant> getValues() const;
private:
std::vector<ValueVariant> m_values;
};
* @param attr - Attribute pointer
*
*/
- void addAttribute(const Attribute &attribute);
+ void addAttribute(const Attribute &attribute, bool overwrite = false);
/**
* API to set range of attribute value.
* @return ID representing update automation session.
* NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
*/
- virtual int startUpdateAutomation(AutomationType type,
+ virtual int startUpdateAutomation(AutomationType type, int updateInterval,
updateCompleteCallback callback) = 0;
/**
*
* @param attrName - Name of the attribute to be automated.
* @param type - Automation type.
+ * @param updateInterval -Interval time in milliseconds for attribute value update automation.
* @param callback - Callback to get notifiy when update automation is finished.
* @param id - Identifier for automation.
*
* NOTE: API throws @InvalidArgsException, @SimulatorException exceptions.
*/
virtual int startUpdateAutomation(const std::string &attrName, AutomationType type,
- updateCompleteCallback callback) = 0;
+ int updateInterval, updateCompleteCallback callback) = 0;
/**
* API to get the Ids of all ongoing resource update automation .
Bundle-ManifestVersion: 2
Bundle-Name: ClientControllerPlugin
Bundle-SymbolicName: ClientControllerPlugin;singleton:=true
-Bundle-Version: 0.1.0
+Bundle-Version: 1.0.0.qualifier
Bundle-Activator: oic.simulator.clientcontroller.Activator
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.graphics.Image;
import org.oic.simulator.ILogger.Level;
-import org.oic.simulator.InvalidArgsException;
import org.oic.simulator.ResourceAttribute;
import org.oic.simulator.ResourceAttribute.Range;
import org.oic.simulator.ResourceAttribute.Type;
// TODO: For debugging
if (null != attributeMap) {
RemoteResourceAttribute.printAttributes(attributeMap);
- System.out.println("Attributes found: ");
+ System.out.println("Attributes found: " + (null != attributeMap));
System.out.println("No of attributes: " + attributeMap.size());
resource.setResourceAttributesMap(attributeMap);
}
public boolean isResourceObserved(String resourceURI) {
- boolean observed;
+ boolean observed = false;
synchronized (observedResourceURIList) {
observed = observedResourceURIList.contains(resourceURI);
}
}
try {
resourceN.stopVerification(autoId);
- } catch (InvalidArgsException e) {
- Activator
- .getDefault()
- .getLogManager()
- .log(Level.ERROR.ordinal(),
- new Date(),
- "[" + e.getClass().getSimpleName() + "]"
- + e.code().toString() + "-"
- + e.message());
- return;
} catch (SimulatorException e) {
Activator
.getDefault()
*/
// TODO: Temporarily adding a resourceType for testing
- // resourceTypeCmb.add("oic.r.light");
+ // resourceTypeCmb.add("oic.r.light");
+ // Currently for standard resources we are using resource type as sample.light.
resourceTypeCmb.add("sample.light");
// By default, selecting the first item in the resourceType combo
import java.util.List;
import oic.simulator.clientcontroller.Activator;
-import oic.simulator.clientcontroller.manager.ResourceManager;
import oic.simulator.clientcontroller.remoteresource.PutPostAttributeModel;
import oic.simulator.clientcontroller.utils.Constants;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.IStructuredContentProvider;
+import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StyledCellLabelProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.swt.SWT;
+import org.eclipse.swt.events.ModifyEvent;
+import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
+import org.eclipse.swt.widgets.Text;
/**
* This dialog is used for generating a POST request.
"Select" };
private final Integer[] attTblColWidth = { 200, 200, 50 };
- private ResourceManager resourceManager;
-
private List<PutPostAttributeModel> modelList = null;
-
+
public PostRequestDialog(Shell parentShell,
List<PutPostAttributeModel> modelList) {
super(parentShell);
this.modelList = modelList;
- resourceManager = Activator.getDefault().getResourceManager();
}
@Override
class AttributeValueEditor extends EditingSupport {
private final TableViewer viewer;
private final CellEditor editor;
-
+ private final Text txt;
public AttributeValueEditor(TableViewer viewer) {
super(viewer);
this.viewer = viewer;
editor = new TextCellEditor(viewer.getTable());
+ txt = (Text)editor.getControl();
+ if(null != txt) {
+ txt.addModifyListener(new ModifyListener() {
+ @Override
+ public void modifyText(ModifyEvent e) {
+ IStructuredSelection selection = (IStructuredSelection)AttributeValueEditor.this.viewer.getSelection();
+ PutPostAttributeModel att = (PutPostAttributeModel)selection.getFirstElement();
+ if(null == att) {
+ return;
+ }
+ String newValue = txt.getText();
+ if(null != newValue && !newValue.isEmpty()) {
+ att.setModified(true);
+ }
+ else {
+ att.setModified(false);
+ }
+ AttributeValueEditor.this.viewer.update(att, null);
+ }
+ });
+
+ }
}
@Override
// If there is a change, then its corresponding check box should be
// checked.
String newValue = String.valueOf(value);
- String actualValue = resourceManager.getAttributeValue(
- resourceManager.getCurrentResourceInSelection(),
- model.getAttName());
- if (newValue.equals(actualValue)) {
- model.setModified(false);
- } else {
- model.setModified(true);
- }
model.setAttValue(newValue);
viewer.update(element, null);
}
.createFromURL(bundle.getEntry("icons/button_pressed.PNG")));
// Resource icons based on the resource type
- r.put(Constants.OIC_R_LIGHT, ImageDescriptor.createFromURL(bundle
+ r.put(Constants.SAMPLE_LIGHT, ImageDescriptor.createFromURL(bundle
.getEntry("/icons/light_16x16.png")));
// Log View related icons
}
public boolean isDisplayName(String displayName) {
- boolean exist;
+ boolean exist = false;
synchronized (displayNameMap) {
exist = displayNameMap.containsKey(displayName);
}
}
public String getCompleteUriFromDisplayName(String displayName) {
- String completeURI;
+ String completeURI = null;
synchronized (displayNameMap) {
completeURI = displayNameMap.get(displayName);
}
@Override
public void run() {
Map<String, SimulatorResource> resourceTypeMap;
- SimulatorResourceServer[] simulatorResourceServers;
+ SimulatorResourceServer[] simulatorResourceServers = null;
try {
simulatorResourceServers = SimulatorManager.createResource(
configFilePath, noOfInstances,
}
public List<String> getURIList() {
- List<String> list;
+ List<String> list = null;
synchronized (orderedResourceUriMap) {
Set<String> typeSet = orderedResourceUriMap.keySet();
List<String> typeList = Utility.convertSetToList(typeSet);
if (null == typeList || typeList.size() < 1) {
- return null;
+ return list;
}
list = new ArrayList<String>();
String attrName = attribute.getAttributeName();
try {
autoId = resourceServerN.startAttributeAutomation(attrName,
- autoType, automationListener);
+ autoType, autoUpdateInterval, automationListener);
} catch (SimulatorException e) {
Activator
.getDefault()
int autoId = -1;
try {
autoId = resourceServer.startResourceAutomation(
- AutomationType.NORMAL, automationListener);
+ AutomationType.NORMAL, 500, automationListener);
} catch (SimulatorException e) {
Activator
.getDefault()
public void shutdown() {
threadHandle.interrupt();
}
-}
+}
\ No newline at end of file
public static final String SPLIT_BY_DOT_PATTERN = "\\.";
- public static final String OIC_R_LIGHT = "oic.r.light";
+ public static final String SAMPLE_LIGHT = "sample.light";
}
\ No newline at end of file
public class AutomationSettingDialog extends TitleAreaDialog {
private CCombo autoTypeCmb;
+ private CCombo updateFreqCmb;
private String automationType;
private String updateFrequencyInMillis;
gd.grabExcessHorizontalSpace = true;
autoTypeCmb.setLayoutData(gd);
+ Label updateFreqLbl = new Label(container, SWT.NONE);
+ updateFreqLbl.setText("Update Frequency(ms)");
+
+ updateFreqCmb = new CCombo(container, SWT.READ_ONLY | SWT.BORDER);
+ gd = new GridData();
+ gd.horizontalAlignment = SWT.FILL;
+ gd.grabExcessHorizontalSpace = true;
+ updateFreqCmb.setLayoutData(gd);
+
populateSettingsData();
addUIListeners();
}
// Select the default value
autoTypeCmb.select(autoTypeCmb.indexOf(value));
+ } else if (settingId.equals(Constants.UPDATE_INTERVAL_IN_MS)) {
+ itr = allowedValues.iterator();
+ while (itr.hasNext()) {
+ updateFreqCmb.add(itr.next());
+ }
+ // Select the default value
+ updateFreqCmb.select(updateFreqCmb.indexOf(value));
}
}
}
automationType = autoTypeCmb.getText();
}
});
+
+ updateFreqCmb.addSelectionListener(new SelectionAdapter() {
+ @Override
+ public void widgetSelected(SelectionEvent e) {
+ updateFrequencyInMillis = updateFreqCmb.getText();
+ }
+ });
}
public void setInitialSettings() {
automationType = autoTypeCmb.getText();
+ updateFrequencyInMillis = updateFreqCmb.getText();
}
public String getAutomationType() {
if (deleteCategory == DeleteCategory.ALL) {
done = true;
} else if (deleteCategory == DeleteCategory.BY_TYPE) {
- int selectedItemIndex = resourceTypeCmb.getSelectionIndex();
- if (selectedItemIndex >= 0) {
- deleteCandidate = resourceTypeCmb.getItem(selectedItemIndex);
- if (null != deleteCandidate && deleteCandidate.length() > 0) {
- done = true;
- }
+ deleteCandidate = resourceTypeCmb.getText();
+ if (null != deleteCandidate && deleteCandidate.length() > 0) {
+ done = true;
}
} else if (deleteCategory == DeleteCategory.BY_URI) {
deleteCandidate = resourceUriTxt.getText();
return static_cast<jobject>(str);
}
-#if 0
// Boolean type value conversion
jobject operator ()(const bool &value) const
{
gSimulatorClassRefs.classBooleanCtor, value);
return result;
}
-
+#if 0
// SimulatorResourceModel::Attribute type value conversion
jobject operator ()(const SimulatorResourceModel::Attribute &value) const
{
jclass classObject;
jclass classInteger;
jclass classDouble;
+ jclass classBoolean;
jclass classString;
jclass classHashMap;
jclass classVector;
jmethodID classIntegerCtor;
jmethodID classDoubleCtor;
+ jmethodID classBooleanCtor;
jmethodID classHashMapCtor;
jmethodID classHashMapPut;
jmethodID classVectorCtor;
return JNI_ERR;
}
+ if (false == getClassRef(env, "java/lang/Boolean", gSimulatorClassRefs.classBoolean))
+ {
+ return JNI_ERR;
+ }
+
if (false == getClassRef(env, "java/lang/String", gSimulatorClassRefs.classString))
{
return JNI_ERR;
if (!gSimulatorClassRefs.classDoubleCtor)
return JNI_ERR;
+ gSimulatorClassRefs.classBooleanCtor= env->GetMethodID(gSimulatorClassRefs.classBoolean, "<init>",
+ "(Z)V");
+ if (!gSimulatorClassRefs.classBooleanCtor)
+ return JNI_ERR;
+
gSimulatorClassRefs.classHashMapCtor = env->GetMethodID(gSimulatorClassRefs.classHashMap, "<init>",
"()V");
if (!gSimulatorClassRefs.classHashMapCtor)
JNIEXPORT jint JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startResourceAutomation
-(JNIEnv *env, jobject object, jint automationType, jobject listener)
+(JNIEnv *env, jobject object, jint automationType, jint updateInterval, jobject listener)
{
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
if (!resource)
try
{
- automationId = resource->startUpdateAutomation(type, callback);
+ automationId = resource->startUpdateAutomation(type, updateInterval, callback);
}
catch (InvalidArgsException &e)
{
JNIEXPORT jint JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startAttributeAutomation
-(JNIEnv *env, jobject object, jstring attrName, jint automationType, jobject listener)
+(JNIEnv *env, jobject object, jstring attrName, jint automationType, jint updateInterval, jobject listener)
{
SimulatorResourceServerSP resource = JniSimulatorResource::getJniSimulatorResourceSP(env, object);
if (!resource)
int automationId = -1;
try
{
- automationId = resource->startUpdateAutomation(attrNamePtr, type, callback);
+ automationId = resource->startUpdateAutomation(attrNamePtr, type, updateInterval, callback);
}
catch (InvalidArgsException &e)
{
JNIEXPORT jint JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startResourceAutomation
-(JNIEnv *, jobject, jint, jobject);
+(JNIEnv *, jobject, jint, jint, jobject);
JNIEXPORT jint JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_startAttributeAutomation
-(JNIEnv *, jobject, jstring, jint, jobject);
+(JNIEnv *, jobject, jstring, jint, jint, jobject);
JNIEXPORT void JNICALL
Java_org_oic_simulator_serviceprovider_SimulatorResourceServer_stopAutomation
protected void finalize() throws Throwable {
try {
dispose();
- }
- finally {
+ } finally {
super.finalize();
}
}
protected void finalize() throws Throwable {
try {
dispose();
- }
- finally {
+ } finally {
super.finalize();
}
}
* @param typeOfAutomation
* {@link AutomationType} indicating whether the automation is
* one-time or recursive.
+ * @param updateInterval
+ * Interval time in milliseconds for attribute value update automation.
* @param listener
* Listener to be notified when automation ends.
*
* This exception will be thrown for other errors.
*/
public int startResourceAutomation(AutomationType typeOfAutomation,
- IAutomation listener) throws InvalidArgsException,
+ int updateInterval, IAutomation listener) throws InvalidArgsException,
SimulatorException {
- return startResourceAutomation(typeOfAutomation.getValue(), listener);
+ return startResourceAutomation(typeOfAutomation.getValue(), updateInterval, listener);
}
/**
* @param typeOfAutomation
* {@link AutomationType} indicating whether the automation is
* one-time or recursive.
+ * @param updateInterval
+ * Interval time in milliseconds for attribute value update automation.
* @param listener
* Listener to be notified when automation ends.
*
* This exception will be thrown for other errors.
*/
public int startAttributeAutomation(String attrName,
- AutomationType typeOfAutomation, IAutomation listener)
+ AutomationType typeOfAutomation, int updateInterval,
+ IAutomation listener)
throws InvalidArgsException, SimulatorException {
return startAttributeAutomation(attrName, typeOfAutomation.getValue(),
- listener);
+ updateInterval, listener);
}
/**
SimulatorException;
private native int startResourceAutomation(int typeOfAutomation,
- IAutomation listener) throws InvalidArgsException,
+ int updateInterval, IAutomation listener) throws InvalidArgsException,
SimulatorException;
private native int startAttributeAutomation(String attrName,
- int typeOfAutomation, IAutomation listener)
+ int typeOfAutomation, int updateInterval, IAutomation listener)
throws InvalidArgsException, SimulatorException;
@Override
protected void finalize() throws Throwable {
try {
dispose();
- }
- finally {
+ } finally {
super.finalize();
}
}
if (*it == reqValue)\r
break;\r
}\r
- if (m_required.end() == it)\r
+ if (m_required.end() != it)\r
{\r
m_required.push_back(reqValue);\r
}\r
if (*it == reqValue)\r
break;\r
}\r
- if (m_required.end() == it)\r
+ if (m_required.end() != it)\r
{\r
m_required.push_back(reqValue);\r
}\r
#include "attribute_generator.h"
-AttributeGenerator::AttributeGenerator(SimulatorResourceModel::Attribute &attribute)
+AttributeGenerator::AttributeGenerator(const SimulatorResourceModel::Attribute &attribute)
: m_name(attribute.getName()),
m_min(INT_MIN),
m_max(INT_MAX),
m_rangeIndex(-1),
- m_nextAllowedValueIndex(0),
- m_prevAllowedValueIndex(0),
+ m_allowedValueIndex(0),
m_hasRange(false),
m_hasAllowedValue(false)
{
{
m_hasAllowedValue = true;
}
- m_prevAllowedValueIndex = m_allowedValues.size();
}
}
return true;
}
- if (m_hasAllowedValue && m_nextAllowedValueIndex < m_allowedValues.size())
+ if (m_hasAllowedValue && m_allowedValueIndex < m_allowedValues.size())
{
return true;
}
}
else if (m_hasAllowedValue)
{
- attribute.setValue(m_allowedValues[m_nextAllowedValueIndex++]);
+ attribute.setValue(m_allowedValues[m_allowedValueIndex++]);
return true;
}
return false;
}
-bool AttributeGenerator::previous(SimulatorResourceModel::Attribute &attribute)
+SimulatorResourceModel::Attribute AttributeGenerator::current()
{
+ SimulatorResourceModel::Attribute attribute;
+
attribute.setName(m_name);
+ if (m_hasRange)
+ {
+ attribute.setValue(m_rangeIndex);
+ }
+ else if (m_hasAllowedValue)
+ {
+ attribute.setValue(m_allowedValues[m_allowedValueIndex]);
+ }
+
+ return attribute;
+}
+void AttributeGenerator::reset()
+{
if (m_hasRange)
{
- attribute.setValue(m_rangeIndex - 1);
- return true;
+ m_rangeIndex = m_min;
}
else if (m_hasAllowedValue)
{
- attribute.setValue(m_allowedValues[m_prevAllowedValueIndex - 1]);
+ m_allowedValueIndex = 0;
+ }
+}
+
+AttributeCombinationGen::AttributeCombinationGen(
+ const std::vector<SimulatorResourceModel::Attribute> &attributes)
+{
+ for (auto &attr : attributes)
+ {
+ AttributeGenerator attrGen(attr);
+ m_attrGenList.push_back(attr);
+ }
+
+ m_index = -1;
+}
+
+bool AttributeCombinationGen::next(SimulatorResourceModel &resModel)
+{
+ if (!m_attrGenList.size())
+ {
+ return false;
+ }
+
+ std::lock_guard<std::mutex> lock(m_lock);
+
+ // This block will execute for only first time
+ if (-1 == m_index)
+ {
+ for (int index = 0; index < m_attrGenList.size(); index++)
+ {
+ // Add the attribute on resource model
+ addAttributeToModel(index);
+ }
+
+ m_index = m_attrGenList.size() - 1;
+ resModel = m_resModel;
+ return true;
+ }
+
+ // Get the next attribute from statck top element
+ if (m_attrGenList[m_index].hasNext())
+ {
+ addAttributeToModel(m_index);
+ resModel = m_resModel;
+ return true;
+ }
+ else
+ {
+ for (int index = m_index; index >= 0; index--)
+ {
+ if (!m_attrGenList[index].hasNext())
+ {
+ if (!index)
+ return false;
+
+ m_attrGenList[index].reset();
+ addAttributeToModel(index);
+ }
+ else
+ {
+ addAttributeToModel(index);
+ break;
+ }
+ }
+
+ resModel = m_resModel;
return true;
}
return false;
}
+void AttributeCombinationGen::addAttributeToModel(int index)
+{
+ SimulatorResourceModel::Attribute attribute;
+ m_attrGenList[index].next(attribute);
+ m_resModel.addAttribute(attribute, true);
+}
class AttributeGenerator
{
public:
- AttributeGenerator(SimulatorResourceModel::Attribute &attribute);
+ AttributeGenerator(const SimulatorResourceModel::Attribute &attribute);
bool hasNext();
bool next(SimulatorResourceModel::Attribute &attribute);
- bool previous(SimulatorResourceModel::Attribute &attribute);
+ SimulatorResourceModel::Attribute current();
void reset();
private:
std::string m_name;
- SimulatorResourceModel::Attribute::ValueType m_type;
int m_min;
int m_max;
int m_rangeIndex;
- int m_nextAllowedValueIndex;
- int m_prevAllowedValueIndex;
+ int m_allowedValueIndex;
bool m_hasRange;
bool m_hasAllowedValue;
std::vector<SimulatorResourceModel::Attribute::ValueVariant> m_allowedValues;
};
+class AttributeCombinationGen
+{
+ public:
+ AttributeCombinationGen(const std::vector<SimulatorResourceModel::Attribute> &attributes);
+ bool next(SimulatorResourceModel &resModel);
+
+ private:
+ void addAttributeToModel(int index);
+
+ std::mutex m_lock;
+ std::vector<AttributeGenerator> m_attrGenList;
+ int m_index;
+ SimulatorResourceModel m_resModel;
+};
+
#endif
OC_LOG(DEBUG, TAG, "Sending OP_START event");
m_callback(m_id, OP_START);
- // Create attribute generator for value manipulation
- std::vector<AttributeGenerator> attributeGenList;
+ // Create attribute combination generator for generating resource model
+ // with different attribute values
+ std::vector<SimulatorResourceModel::Attribute> attributes;
for (auto &attributeElement : m_rep->getAttributes())
- attributeGenList.push_back(AttributeGenerator(attributeElement.second));
+ {
+ attributes.push_back(attributeElement.second);
+ }
- if (!attributeGenList.size())
+ if (!attributes.size())
{
OC_LOG(ERROR, TAG, "Zero attribute found from resource model!");
return;
}
- bool hasNext = false;
-
do
{
- if (!m_stopRequested)
+ if (m_stopRequested)
{
- // Get the next possible queryParameter
- std::map<std::string, std::string> queryParam = m_queryParamGen.next();
-
- while (true)
- {
- SimulatorResourceModelSP repModel(new SimulatorResourceModel);
- for (auto & attributeGen : attributeGenList)
- {
- if (attributeGen.hasNext())
- {
- SimulatorResourceModel::Attribute attribute;
- if (true == attributeGen.next(attribute))
- repModel->addAttribute(attribute);
-
- hasNext = true;
- }
- else
- {
- SimulatorResourceModel::Attribute attribute;
- if (true == attributeGen.previous(attribute))
- repModel->addAttribute(attribute);
- }
- }
-
- if (hasNext)
- {
- // Send the request
- m_requestSender->sendRequest(queryParam, repModel,
- std::bind(&PUTRequestGenerator::onResponseReceived, this,
- std::placeholders::_1, std::placeholders::_2), true);
-
- m_requestCnt++;
- hasNext = false;
- continue;
- }
- else
- {
- break;
- }
- }
+ break;
+ }
+
+ // Get the next possible queryParameter
+ std::map<std::string, std::string> queryParam = m_queryParamGen.next();
+
+ AttributeCombinationGen attrCombGen(attributes);
+
+ // Get the new model from attribute combination generator
+ SimulatorResourceModel resModel;
+ while (!m_stopRequested && attrCombGen.next(resModel))
+ {
+ SimulatorResourceModelSP repModel(new SimulatorResourceModel(resModel));
+
+ // Send the request
+ m_requestSender->sendRequest(queryParam, repModel,
+ std::bind(&PUTRequestGenerator::onResponseReceived, this,
+ std::placeholders::_1, std::placeholders::_2), true);
+
+ m_requestCnt++;
}
}
while (m_queryParamGen.hasNext());
if (m_getRequestSender)
{
return m_autoRequestGenMngr->startOnGET(m_getRequestSender,
- m_requestModelList[RequestType::RQ_TYPE_GET]->getQueryParams(),
- localCallback);
+ m_requestModelList[RequestType::RQ_TYPE_GET]->getQueryParams(),
+ localCallback);
}
break;
if (m_putRequestSender)
{
return m_autoRequestGenMngr->startOnPUT(m_putRequestSender,
- m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(),
- m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(),
- localCallback);
+ m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(),
+ m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(),
+ localCallback);
}
break;
if (m_postRequestSender)
{
return m_autoRequestGenMngr->startOnPOST(m_putRequestSender,
- m_requestModelList[RequestType::RQ_TYPE_POST]->getQueryParams(),
- m_requestModelList[RequestType::RQ_TYPE_POST]->getRepSchema(),
- localCallback);
+ m_requestModelList[RequestType::RQ_TYPE_POST]->getQueryParams(),
+ m_requestModelList[RequestType::RQ_TYPE_POST]->getRepSchema(),
+ localCallback);
}
break;
{
std::vector<SimulatorResourceModel::Attribute::ValueVariant> values
= m_attrItem.getAllowedValues();
+ if(0 == values.size())
+ return true;
for (SimulatorResourceModel::Attribute::ValueVariant & val : values)
{
SimulatorResourceModel::Attribute::ValueVariant vVal = value;
{
std::vector<SimulatorResourceModel::Attribute::ValueVariant> values
= m_attrItem.getAllowedValues();
+ if(0 == values.size())
+ return true;
for (SimulatorResourceModel::Attribute::ValueVariant & vVal : values)
{
std::string val = boost::get<std::string>(vVal);
}
std::vector<SimulatorResourceModel::Attribute::ValueVariant>
-SimulatorResourceModel::Attribute::AllowedValues::getValues()
+SimulatorResourceModel::Attribute::AllowedValues::getValues() const
{
return m_values;
}
}
std::vector<SimulatorResourceModel::Attribute::ValueVariant>
-SimulatorResourceModel::Attribute::getAllowedValues()
+SimulatorResourceModel::Attribute::getAllowedValues() const
{
return m_allowedValues.getValues();
}
return m_attributes;
}
-void SimulatorResourceModel::addAttribute(const SimulatorResourceModel::Attribute &attribute)
+void SimulatorResourceModel::addAttribute(const SimulatorResourceModel::Attribute &attribute, bool overwrite)
{
if (!attribute.getName().empty() &&
- m_attributes.end() == m_attributes.find(attribute.getName()))
+ (m_attributes.end() == m_attributes.find(attribute.getName()) || overwrite))
{
m_attributes[attribute.getName()] = attribute;
}
attribute.setValue(attributeItem.getValue<double>());
if (attributeItem.type() == OC::AttributeType::String)
attribute.setValue(attributeItem.getValue<std::string>());
+ if (attributeItem.type() == OC::AttributeType::Boolean)
+ attribute.setValue(attributeItem.getValue<bool>());
attribute.setName(attributeItem.attrname());
resModel->m_attributes[attributeItem.attrname()] = attribute;
#include "resource_update_automation.h"
#include "simulator_resource_server_impl.h"
+#include "attribute_generator.h"
#include "simulator_exceptions.h"
#include "simulator_logger.h"
#include "logger.h"
SIM_LOG(ILogger::INFO, "Automation of " << m_attrName << " attribute is completed.");
}
- // Notify application through callback
+ // Notify application
if (m_callback)
m_callback(m_resource->getURI(), m_id);
: m_resource(resource),
m_type(type),
m_id(id),
+ m_stopRequested(false),
m_updateInterval(interval),
m_callback(callback),
- m_finishedCallback(finishedCallback) {}
+ m_finishedCallback(finishedCallback),
+ m_thread(nullptr) {}
void ResourceUpdateAutomation::start()
{
- m_resModel = m_resource->getModel();
- std::map<std::string, SimulatorResourceModel::Attribute> attributes = m_resModel.getAttributes();
- if (0 == attributes.size())
+ SimulatorResourceModel resModel = m_resource->getModel();
+ std::map<std::string, SimulatorResourceModel::Attribute> attributesTable =
+ resModel.getAttributes();
+ if (0 == attributesTable.size())
{
OC_LOG(ERROR, RTAG, "Resource has zero attributes!");
throw SimulatorException(SIMULATOR_ERROR, "Resource has zero attributes!");
}
- int id = 0;
- for (auto & attribute : attributes)
- {
- AttributeUpdateAutomationSP attributeAutomation(new AttributeUpdateAutomation(
- id, m_resource, attribute.first, m_type, m_updateInterval, nullptr,
- std::bind(&ResourceUpdateAutomation::finished, this, std::placeholders::_1)));
+ std::vector<SimulatorResourceModel::Attribute> attributes;
+ for (auto &attributeEntry : attributesTable)
+ attributes.push_back(attributeEntry.second);
- m_attrUpdationList[id++] = attributeAutomation;
- try
- {
- attributeAutomation->start();
- }
- catch (SimulatorException &e)
- {
- stop();
- throw;
- }
- }
+ m_thread = new std::thread(&ResourceUpdateAutomation::updateAttributes, this, attributes);
}
-void ResourceUpdateAutomation::finished(int id)
+void ResourceUpdateAutomation::stop()
{
- if (m_attrUpdationList.end() != m_attrUpdationList.find(id))
- {
- m_attrUpdationList.erase(m_attrUpdationList.find(id));
- }
-
- if (!m_attrUpdationList.size())
- {
- // Notify application through callback
- if (m_callback)
- m_callback(m_resource->getURI(), m_id);
-
- if (m_finishedCallback)
- m_finishedCallback(m_id);
- }
+ m_stopRequested = true;
+ if (m_thread)
+ m_thread->join();
}
-void ResourceUpdateAutomation::stop()
+void ResourceUpdateAutomation::updateAttributes(
+ std::vector<SimulatorResourceModel::Attribute> attributes)
{
- // Stop all the attributes updation
- for (auto & attrAutomation : m_attrUpdationList)
+ SimulatorResourceServerImpl *resourceImpl =
+ dynamic_cast<SimulatorResourceServerImpl *>(m_resource);
+
+ AttributeCombinationGen attrCombGen(attributes);
+ SimulatorResourceModel resModel;
+ while (!m_stopRequested && attrCombGen.next(resModel))
{
- (attrAutomation.second)->stop();
+ for (auto &attributeEntry : resModel.getAttributes())
+ {
+ resourceImpl->updateAttributeValue(attributeEntry.first, attributeEntry.second.getValue());
+ }
+
+ resourceImpl->notifyApp();
+ SLEEP_FOR(m_updateInterval);
}
- m_attrUpdationList.clear();
+ // Notify application
+ if (m_callback)
+ m_callback(m_resource->getURI(), m_id);
+
+ if (m_finishedCallback && !m_stopRequested)
+ m_finishedCallback(m_id);
}
+
void stop();
- void finished(int id);
-
private:
+ void updateAttributes(std::vector<SimulatorResourceModel::Attribute> attributes);
+
SimulatorResourceServer *m_resource;
AutomationType m_type;
int m_id;
+ bool m_stopRequested;
int m_updateInterval;
- SimulatorResourceModel m_resModel;
- std::map<int, AttributeUpdateAutomationSP> m_attrUpdationList;
updateCompleteCallback m_callback;
std::function<void (const int)> m_finishedCallback;
+ std::thread *m_thread;
};
typedef std::shared_ptr<ResourceUpdateAutomation> ResourceUpdateAutomationSP;
}
int SimulatorResourceServerImpl::startUpdateAutomation(AutomationType type,
- updateCompleteCallback callback)
+ int updateInterval, updateCompleteCallback callback)
{
if (!callback)
{
throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
}
- // This fix is temporarily to give 500 ms default delay in automation until the new UI change is merged.
- return m_updateAutomationMgr.startResourceAutomation(this, type, 500, callback);
+ return m_updateAutomationMgr.startResourceAutomation(this, type, updateInterval, callback);
}
int SimulatorResourceServerImpl::startUpdateAutomation(const std::string &attrName,
- AutomationType type,
+ AutomationType type, int updateInterval,
updateCompleteCallback callback)
{
if (!callback)
throw SimulatorException(SIMULATOR_NO_RESOURCE, "Invalid resource!");
}
- // This fix is temporarily to give 500 ms default delay in automation until the new UI change is merged.
- return m_updateAutomationMgr.startAttributeAutomation(this, attrName, type, 500, callback);
+ return m_updateAutomationMgr.startAttributeAutomation(this, attrName, type, updateInterval, callback);
}
std::vector<int> SimulatorResourceServerImpl::getResourceAutomationIds()
bool isObservable() const;
- int startUpdateAutomation(AutomationType type,
+ int startUpdateAutomation(AutomationType type, int updateInterval,
updateCompleteCallback callback);
int startUpdateAutomation(const std::string &attrName, AutomationType type,
- updateCompleteCallback callback);
+ int updateInterval, updateCompleteCallback callback);
std::vector<int> getResourceAutomationIds();