author
int64 658
755k
| date
stringlengths 19
19
| timezone
int64 -46,800
43.2k
| hash
stringlengths 40
40
| message
stringlengths 5
490
| mods
list | language
stringclasses 20
values | license
stringclasses 3
values | repo
stringlengths 5
68
| original_message
stringlengths 12
491
|
---|---|---|---|---|---|---|---|---|---|
89,734 | 19.06.2019 15:37:16 | -7,200 | 9eb81be5cee9decf100435d42065c9e74d5871e4 | fix: normalize the reference intervals
Differential FVA was only normalizing the grid point flux ranges but not
the reference state. That means they were essentially in different
dimensions when computing the gaps between intervals. | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -322,6 +322,17 @@ class DifferentialFVA(StrainDesignMethod):\nsolutions = dict((tuple(point.iteritems()), fva_result) for (point, fva_result) in results)\nreference_intervals = self.reference_flux_ranges[['lower_bound', 'upper_bound']].values\n+ if self.normalize_ranges_by is not None:\n+ norm = reference_intervals.lower_bound[self.normalize_ranges_by]\n+ if norm > non_zero_flux_threshold:\n+ normalized_reference_intervals = reference_intervals[['lower_bound', 'upper_bound']].values / norm\n+ else:\n+ raise ValueError(\n+ \"The reaction that you have chosen for normalization '{}' \"\n+ \"has zero flux in the reference state. Please choose another \"\n+ \"one.\".format(self.normalize_ranges_by)\n+ )\n+\nfor sol in six.itervalues(solutions):\nintervals = sol[['lower_bound', 'upper_bound']].values\ngaps = [self._interval_gap(interval1, interval2) for interval1, interval2 in\n@@ -333,7 +344,8 @@ class DifferentialFVA(StrainDesignMethod):\nnormalized_intervals = sol[['lower_bound', 'upper_bound']].values / normalizer\nsol['normalized_gaps'] = [self._interval_gap(interval1, interval2) for interval1, interval2 in\n- my_zip(reference_intervals, normalized_intervals)]\n+ my_zip(normalized_reference_intervals,\n+ normalized_intervals)]\nelse:\nsol['normalized_gaps'] = [numpy.nan] * len(sol.lower_bound)\nelse:\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: normalize the reference intervals
Differential FVA was only normalizing the grid point flux ranges but not
the reference state. That means they were essentially in different
dimensions when computing the gaps between intervals. |
89,734 | 19.06.2019 15:39:52 | -7,200 | a5afbec803125aaca23d37a824f7776e4f35db42 | fix: use absolute values for normalization | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -323,7 +323,13 @@ class DifferentialFVA(StrainDesignMethod):\nsolutions = dict((tuple(point.iteritems()), fva_result) for (point, fva_result) in results)\nreference_intervals = self.reference_flux_ranges[['lower_bound', 'upper_bound']].values\nif self.normalize_ranges_by is not None:\n- norm = reference_intervals.lower_bound[self.normalize_ranges_by]\n+ # The most obvious flux to normalize by is the biomass reaction\n+ # flux. This is probably always greater than zero. Just in case\n+ # the model is defined differently or some other normalizing\n+ # reaction is chosen, we use the absolute value.\n+ norm = abs(\n+ reference_intervals.lower_bound[self.normalize_ranges_by]\n+ )\nif norm > non_zero_flux_threshold:\nnormalized_reference_intervals = reference_intervals[['lower_bound', 'upper_bound']].values / norm\nelse:\n@@ -339,7 +345,8 @@ class DifferentialFVA(StrainDesignMethod):\nmy_zip(reference_intervals, intervals)]\nsol['gaps'] = gaps\nif self.normalize_ranges_by is not None:\n- normalizer = sol.lower_bound[self.normalize_ranges_by]\n+ # See comment above regarding normalization.\n+ normalizer = abs(sol.lower_bound[self.normalize_ranges_by])\nif normalizer > non_zero_flux_threshold:\nnormalized_intervals = sol[['lower_bound', 'upper_bound']].values / normalizer\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: use absolute values for normalization |
89,734 | 19.06.2019 15:43:40 | -7,200 | b34dd4bed3a0cd7876f6b65e370499f20b3fc5ca | fix: exclude more than one variable | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -182,6 +182,14 @@ class DifferentialFVA(StrainDesignMethod):\nself.variables.append(variable.id)\nelse:\nself.variables.append(variable)\n+ if len(self.variables) > 1:\n+ raise NotImplementedError(\n+ \"We also think that searching the production envelope over \"\n+ \"more than one variable would be a neat feature. However, \"\n+ \"at the moment there are some assumptions in the code that \"\n+ \"prevent this and we don't have the resources to change it. \"\n+ \"Pull request welcome ;-)\"\n+ )\nself.exclude = list()\nfor elem in exclude:\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: exclude more than one variable |
89,734 | 19.06.2019 16:08:45 | -7,200 | b3cf457d9a85b0ddc0aaefd241b2930d2c84c89e | fix: correct the conditions for suddenly essential | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -371,6 +371,11 @@ class DifferentialFVA(StrainDesignMethod):\nref_lower_bound = self.reference_flux_ranges.lower_bound.apply(\nlambda v: 0 if abs(v) < non_zero_flux_threshold else v)\n+ # Determine where the reference flux range overlaps with zero.\n+ zero_overlap_mask = numpy.asarray([\n+ self._interval_overlap(interval1, (0, 0)) > 0\n+ for interval1 in reference_intervals\n+ ], dtype=bool)\ncollection = list()\nfor key, df in six.iteritems(solutions):\ndf['biomass'] = key[0][1]\n@@ -396,8 +401,8 @@ class DifferentialFVA(StrainDesignMethod):\n] = True\ndf.loc[\n- ((df.lower_bound <= 0) & (df.lower_bound > 0)) | (\n- (ref_lower_bound >= 0) & (df.upper_bound <= 0)),\n+ (zero_overlap_mask & (df.lower_bound > 0)) | (\n+ zero_overlap_mask & (df.upper_bound < 0)),\n'suddenly_essential'\n] = True\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: correct the conditions for suddenly essential |
89,734 | 19.06.2019 19:28:36 | -7,200 | 390310d08b06d57383399975e55e953476d375f3 | fix: change included reactions | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -224,6 +224,15 @@ class DifferentialFVA(StrainDesignMethod):\nelse:\nself.normalize_ranges_by = normalize_ranges_by\n+ self.included_reactions = {\n+ r.id for r in self.reference_model.reactions\n+ if r.id not in self.exclude\n+ }\n+ # Re-introduce key reactions in case they were excluded.\n+ self.included_reactions.update(self.variables)\n+ self.included_reactions.add(self.objective)\n+ self.included_reactions.add(self.normalize_ranges_by)\n+\n@staticmethod\ndef _interval_overlap(interval1, interval2):\nreturn min(interval1[1] - interval2[0], interval2[1] - interval1[0])\n@@ -309,19 +318,27 @@ class DifferentialFVA(StrainDesignMethod):\nelse:\nview = view\n- included_reactions = [reaction.id for reaction in self.reference_model.reactions if\n- reaction.id not in self.exclude] + self.variables + [self.objective]\n-\n- self.reference_flux_dist = pfba(self.reference_model, fraction_of_optimum=0.99)\n+ self.reference_flux_dist = pfba(\n+ self.reference_model,\n+ fraction_of_optimum=0.99\n+ )\n- self.reference_flux_ranges = flux_variability_analysis(self.reference_model, reactions=included_reactions,\n- view=view, remove_cycles=False,\n- fraction_of_optimum=0.75).data_frame\n+ self.reference_flux_ranges = flux_variability_analysis(\n+ self.reference_model,\n+ reactions=self.included_reactions,\n+ view=view,\n+ remove_cycles=False,\n+ fraction_of_optimum=0.75\n+ ).data_frame\nself._init_search_grid(surface_only=surface_only, improvements_only=improvements_only)\n- func_obj = _DifferentialFvaEvaluator(self.design_space_model, self.variables, self.objective,\n- included_reactions)\n+ func_obj = _DifferentialFvaEvaluator(\n+ self.design_space_model,\n+ self.variables,\n+ self.objective,\n+ self.included_reactions\n+ )\nif progress:\nprogress = ProgressBar(len(self.grid))\nresults = list(progress(view.imap(func_obj, self.grid.iterrows())))\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: change included reactions |
89,734 | 19.06.2019 19:29:14 | -7,200 | 8636525c58f59cde1fbf634fc10c04fbf9d0ea83 | fix: use correct data structures | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -353,10 +353,10 @@ class DifferentialFVA(StrainDesignMethod):\n# the model is defined differently or some other normalizing\n# reaction is chosen, we use the absolute value.\nnorm = abs(\n- reference_intervals.lower_bound[self.normalize_ranges_by]\n+ self.reference_flux_ranges.lower_bound[self.normalize_ranges_by]\n)\nif norm > non_zero_flux_threshold:\n- normalized_reference_intervals = reference_intervals[['lower_bound', 'upper_bound']].values / norm\n+ normalized_reference_intervals = reference_intervals / norm\nelse:\nraise ValueError(\n\"The reaction that you have chosen for normalization '{}' \"\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: use correct data structures |
89,734 | 19.06.2019 20:31:52 | -7,200 | 170471cc56ae3822632348518b091d4f1215c9ef | fix: special case when norm is None | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -231,6 +231,7 @@ class DifferentialFVA(StrainDesignMethod):\n# Re-introduce key reactions in case they were excluded.\nself.included_reactions.update(self.variables)\nself.included_reactions.add(self.objective)\n+ if self.normalize_ranges_by is not None:\nself.included_reactions.add(self.normalize_ranges_by)\n@staticmethod\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: special case when norm is None |
89,734 | 24.06.2019 10:55:21 | -7,200 | 338a734f70da08b0899ca6acc70223c48fcf6a43 | fix: return copy of panel | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -605,7 +605,7 @@ class DifferentialFVAResult(StrainDesignMethodResult):\n\"\"\"\ngrouped = self.solutions.groupby(['biomass', 'production'],\nas_index=False, sort=False)\n- return grouped.get_group(sorted(grouped.groups.keys())[index])\n+ return grouped.get_group(sorted(grouped.groups.keys())[index]).copy()\ndef plot(self, index=None, variables=None, grid=None, width=None, height=None, title=None, palette=None, **kwargs):\nif index is not None:\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: return copy of panel |
89,734 | 24.06.2019 12:26:35 | -7,200 | bf0a1f1b47bdef11b696cbed5efcff0c194b6b80 | fix: align intervals
The reference flux ranges were unaligned with the point solutions. Thus
gaps were calculated over the wrong intervals. | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -233,6 +233,7 @@ class DifferentialFVA(StrainDesignMethod):\nself.included_reactions.add(self.objective)\nif self.normalize_ranges_by is not None:\nself.included_reactions.add(self.normalize_ranges_by)\n+ self.included_reactions = sorted(self.included_reactions)\n@staticmethod\ndef _interval_overlap(interval1, interval2):\n@@ -322,16 +323,20 @@ class DifferentialFVA(StrainDesignMethod):\nremove_cycles=False,\nfraction_of_optimum=fraction_of_optimum\n).data_frame\n- reference_intervals = self.reference_flux_ranges[['lower_bound', 'upper_bound']].values\n+ reference_intervals = self.reference_flux_ranges.loc[\n+ self.included_reactions,\n+ ['lower_bound', 'upper_bound']\n+ ].values\nif self.normalize_ranges_by is not None:\n- logger.info(self.reference_flux_ranges.loc[self.normalize_ranges_by, ])\n+ logger.debug(self.reference_flux_ranges.loc[self.normalize_ranges_by, ])\n# The most obvious flux to normalize by is the biomass reaction\n# flux. This is probably always greater than zero. Just in case\n# the model is defined differently or some other normalizing\n# reaction is chosen, we use the absolute value.\nnorm = abs(\n- self.reference_flux_ranges.lower_bound[self.normalize_ranges_by]\n+ self.reference_flux_ranges.at[self.normalize_ranges_by,\n+ \"lower_bound\"]\n)\nif norm > non_zero_flux_threshold:\nnormalized_reference_intervals = reference_intervals / norm\n@@ -374,21 +379,30 @@ class DifferentialFVA(StrainDesignMethod):\nsolutions = dict((tuple(point.iteritems()), fva_result) for (point, fva_result) in results)\nfor sol in six.itervalues(solutions):\n- intervals = sol[['lower_bound', 'upper_bound']].values\n- gaps = [self._interval_gap(interval1, interval2) for interval1, interval2 in\n- my_zip(reference_intervals, intervals)]\n+ intervals = sol.loc[\n+ self.included_reactions,\n+ ['lower_bound', 'upper_bound']\n+ ].values\n+ gaps = [\n+ self._interval_gap(interval1, interval2)\n+ for interval1, interval2 in my_zip(reference_intervals, intervals)\n+ ]\nsol['gaps'] = gaps\nif self.normalize_ranges_by is not None:\n# See comment above regarding normalization.\nnormalizer = abs(sol.lower_bound[self.normalize_ranges_by])\nif normalizer > non_zero_flux_threshold:\n- normalized_intervals = sol[['lower_bound', 'upper_bound']].values / normalizer\n-\n- sol['normalized_gaps'] = [self._interval_gap(interval1, interval2) for interval1, interval2 in\n- my_zip(normalized_reference_intervals,\n- normalized_intervals)]\n+ normalized_intervals = sol.loc[\n+ self.included_reactions,\n+ ['lower_bound', 'upper_bound']\n+ ].values / normalizer\n+\n+ sol['normalized_gaps'] = [\n+ self._interval_gap(interval1, interval2)\n+ for interval1, interval2 in my_zip(\n+ normalized_reference_intervals, normalized_intervals)]\nelse:\n- sol['normalized_gaps'] = [numpy.nan] * len(sol.lower_bound)\n+ sol['normalized_gaps'] = numpy.nan\nelse:\nsol['normalized_gaps'] = gaps\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: align intervals
The reference flux ranges were unaligned with the point solutions. Thus
gaps were calculated over the wrong intervals. |
89,734 | 24.06.2019 12:53:37 | -7,200 | 331adc12f1578058657ca5ea66f213e875e38b3a | chore: change default fraction to 1.0 | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -286,7 +286,7 @@ class DifferentialFVA(StrainDesignMethod):\nself.grid = DataFrame(grid, columns=columns)\ndef run(self, surface_only=True, improvements_only=True, progress=True,\n- view=None, fraction_of_optimum=0.99):\n+ view=None, fraction_of_optimum=1.0):\n\"\"\"Run the differential flux variability analysis.\nParameters\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | chore: change default fraction to 1.0 |
89,734 | 24.06.2019 13:03:17 | -7,200 | 313406d1741407c9980854a5803f05ed0f52c5a3 | fix: do not constrain objective
Fixing the objective is automatically done by FVA. It is thus not
necessary here. | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -143,7 +143,6 @@ class DifferentialFVA(StrainDesignMethod):\nself.design_space_nullspace = nullspace(create_stoichiometric_array(self.design_space_model))\nif reference_model is None:\nself.reference_model = self.design_space_model.copy()\n- fix_objective_as_constraint(self.reference_model)\nself.reference_nullspace = self.design_space_nullspace\nelse:\nself.reference_model = reference_model\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: do not constrain objective
Fixing the objective is automatically done by FVA. It is thus not
necessary here. |
89,734 | 24.06.2019 14:22:18 | -7,200 | 8e5396a9a6d7060b0f38881709a4cff3e5661a33 | chore: update test data generation script | [
{
"change_type": "MODIFY",
"old_path": "tests/data/REFERENCE_DiffFVA1.csv",
"new_path": "tests/data/REFERENCE_DiffFVA1.csv",
"diff": "-,upper_bound,lower_bound,gaps,normalized_gaps,KO,flux_reversal,suddenly_essential,free_flux,excluded\n-ACALD,0.0,0.0,0.0,0.0,False,False,False,False,False\n-ACALDt,0.0,0.0,0.0,0.0,False,False,False,False,False\n-ACKr,0.0,0.0,0.0,0.0,False,False,False,False,False\n-ACONTa,3.615833333333285,3.615833333333285,0.0,0.0,False,False,False,False,False\n-ACONTb,3.615833333333285,3.615833333333285,0.0,0.0,False,False,False,False,False\n-ACt2r,0.0,0.0,0.0,0.0,False,False,False,False,False\n-ADK1,2.7683333333328806,2.7683333333328806,0.0,0.0,False,False,False,False,False\n-AKGDH,0.0,0.0,0.0,0.0,False,False,True,False,False\n-AKGt2r,0.0,0.0,0.0,0.0,False,False,False,False,False\n-ALCD2x,0.0,0.0,0.0,0.0,False,False,False,False,False\n-ATPM,8.39,8.39,0.0,0.0,False,False,False,False,False\n-ATPS4r,3.9266666666661836,3.9266666666661836,-19.82634819193459,-19.82634819193459,False,False,False,False,False\n-Biomass_Ecoli_core_N_lp_w_fsh_GAM_rp__Nmet2,0.0,0.0,-0.6554411302263228,-0.6554411302263228,True,False,True,False,True\n-CO2t,5.536666666666456,5.536666666666456,-14.29260754190473,-14.29260754190473,False,True,False,False,False\n-CS,3.615833333333285,3.615833333333285,0.0,0.0,False,False,False,False,False\n-CYTBD,5.310833333332994,5.310833333332994,-20.62150419557218,-20.62150419557218,False,False,False,False,False\n-D_LACt2,0.0,0.0,0.0,0.0,False,False,False,False,False\n-ENO,20.0,20.0,2.722899087299215,2.722899087299215,False,False,False,False,False\n-ETOHt2r,0.0,0.0,0.0,0.0,False,False,False,False,False\n-EX_succ_lp_e_rp_,16.38416666666667,16.38416666666667,12.204559811281978,12.204559811281978,False,False,False,False,True\n-FBA,10.0,10.0,0.6519672922361242,0.6519672922361242,False,False,False,False,False\n-FBP,0.0,0.0,0.0,0.0,False,False,True,False,False\n-FORt2,0.0,0.0,0.0,0.0,False,False,True,False,False\n-FORti,0.0,0.0,0.0,0.0,False,False,True,False,False\n-FRD7,1000.0,12.768333333333338,0.0,0.0,False,False,False,False,False\n-FRUpts2,0.0,0.0,0.0,0.0,False,False,True,False,False\n-FUM,-12.76833333333343,-12.76833333333343,9.834047715695874,9.834047715695874,False,False,False,False,False\n-FUMt2_2,0.0,0.0,0.0,0.0,False,False,True,False,False\n-G6PDH2r,0.0,0.0,0.0,0.0,False,False,True,False,False\n-GAPD,20.0,20.0,1.742359156480635,1.742359156480635,False,False,False,False,False\n-GLCpts,10.0,10.0,0.0,0.0,False,False,False,False,False\n-GLNS,0.0,0.0,-0.16759629699887071,-0.16759629699887071,True,False,True,False,False\n-GLNabc,0.0,0.0,0.0,0.0,False,False,True,False,False\n-GLUDy,0.0,0.0,0.0,0.0,True,False,False,False,False\n-GLUN,0.0,0.0,0.0,0.0,False,False,True,False,False\n-GLUSy,0.0,0.0,0.0,0.0,False,False,True,False,False\n-GLUt2r,0.0,0.0,0.0,0.0,False,False,False,False,False\n-GND,0.0,0.0,0.0,0.0,False,False,True,False,False\n-H2Ot,-10.847500000000203,-10.847500000000203,-2.6829362442587126,-2.6829362442587126,False,False,False,False,False\n-ICDHyr,0.0,0.0,-0.7071554354011798,-0.7071554354011798,True,False,True,False,False\n-ICL,3.615833333333285,3.615833333333285,0.0,0.0,False,False,False,False,False\n-LDH_D,0.0,0.0,0.0,0.0,False,False,False,False,False\n-MALS,3.615833333333285,3.615833333333285,0.0,0.0,False,False,False,False,False\n-MALt2_2,0.0,0.0,0.0,0.0,False,False,True,False,False\n-MDH,-9.152500000000146,-9.152500000000146,0.0,0.0,False,False,False,False,False\n-ME1,0.0,0.0,0.0,0.0,False,False,True,False,False\n-ME2,0.0,0.0,0.0,0.0,False,False,True,False,False\n-NADH16,18.079166666666424,18.079166666666424,-6.9801126433205525,-6.9801126433205525,False,False,False,False,False\n-NADTRHD,0.0,0.0,0.0,0.0,False,False,True,False,False\n-NH4t,0.0,0.0,-3.573989394898093,-3.573989394898093,True,False,True,False,False\n-O2t,2.655416666666497,2.655416666666497,-10.310752097786088,-10.310752097786088,False,False,False,False,False\n-PDH,7.23166666666657,7.23166666666657,0.0,0.0,False,False,False,False,False\n-PFK,9.99999999999945,9.99999999999945,0.0,0.0,False,False,False,False,False\n-PFL,0.0,0.0,0.0,0.0,False,False,True,False,False\n-PGI,10.0,10.0,0.1343654316963967,0.1343654316963967,False,False,False,False,False\n-PGK,-20.00000000000017,-20.00000000000017,1.7423591564808092,1.7423591564808092,False,False,False,False,False\n-PGL,0.0,0.0,0.0,0.0,False,False,True,False,False\n-PGM,-20.00000000000017,-20.00000000000017,2.722899087299382,2.722899087299382,False,False,False,False,False\n-PIt2r,0.0,0.0,-2.4111712857635705,-2.4111712857635705,True,False,True,False,False\n-PPC,12.76833333333343,12.76833333333343,0.0,0.0,False,False,False,False,False\n-PPCK,0.0,0.0,0.0,0.0,False,False,True,False,False\n-PPS,2.7683333333328806,2.7683333333328806,0.0,0.0,False,False,False,False,False\n-PTAr,0.0,0.0,0.0,0.0,False,False,True,False,False\n-PYK,0.0,0.0,0.0,0.0,False,False,True,False,False\n-PYRt2r,0.0,0.0,0.0,0.0,False,False,False,False,False\n-RPE,0.0,0.0,0.0,0.0,True,False,False,False,False\n-RPI,0.0,0.0,-0.47113108440668083,-0.47113108440668083,True,False,False,False,False\n-SUCCt2_2,0.0,0.0,0.0,0.0,False,False,True,False,False\n-SUCCt3,16.38416666666588,16.38416666666588,0.0,0.0,False,False,False,False,False\n-SUCDi,987.2316666666666,0.0,0.0,0.0,False,False,False,False,False\n-SUCOAS,0.0,0.0,0.0,0.0,False,False,False,False,False\n-TALA,0.0,0.0,0.0,0.0,True,False,False,False,False\n-THD2,0.0,0.0,0.0,0.0,False,False,True,False,False\n-TKT1,0.0,0.0,0.0,0.0,True,False,False,False,False\n-TKT2,0.0,0.0,0.0,0.0,True,False,False,False,False\n-TPI,10.0,10.0,0.6519672922361242,0.6519672922361242,False,False,False,False,False\n+,lower_bound,upper_bound,gaps,normalized_gaps,biomass,production,KO,flux_reversal,suddenly_essential,free_flux,reaction,excluded\n+ACALD,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACALD,False\n+ACALDt,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACALDt,False\n+ACKr,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACKr,False\n+ACONTa,3.616,3.616,-2.391,-2.391,0.000,16.384,False,False,False,False,ACONTa,False\n+ACONTb,3.616,3.616,-2.391,-2.391,0.000,16.384,False,False,False,False,ACONTb,False\n+ACt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACt2r,False\n+ADK1,2.768,2.768,2.768,2.768,0.000,16.384,False,False,False,False,ADK1,False\n+AKGDH,0.000,0.000,-5.064,-5.064,0.000,16.384,True,False,False,False,AKGDH,False\n+AKGt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,AKGt2r,False\n+ALCD2x,0.000,0.000,-0.000,-0.000,0.000,16.384,False,False,False,False,ALCD2x,False\n+ATPM,8.390,8.390,0.000,0.000,0.000,16.384,False,False,False,False,ATPM,False\n+ATPS4r,3.927,3.927,-41.587,-41.587,0.000,16.384,False,False,False,False,ATPS4r,False\n+Biomass_Ecoli_core_N_lp_w_fsh_GAM_rp__Nmet2,0.000,0.000,-0.874,-0.874,0.000,16.384,True,False,False,False,Biomass_Ecoli_core_N_lp_w_fsh_GAM_rp__Nmet2,True\n+CO2t,5.537,5.537,-28.346,-28.346,0.000,16.384,False,True,False,False,CO2t,False\n+CS,3.616,3.616,-2.391,-2.391,0.000,16.384,False,False,False,False,CS,False\n+CYTBD,5.311,5.311,-38.288,-38.288,0.000,16.384,False,False,False,False,CYTBD,False\n+D_LACt2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,D_LACt2,False\n+ENO,20.000,20.000,5.284,5.284,0.000,16.384,False,False,False,False,ENO,False\n+ETOHt2r,0.000,0.000,-0.000,-0.000,0.000,16.384,False,False,False,False,ETOHt2r,False\n+EX_succ_lp_e_rp_,16.384,16.384,16.384,16.384,0.000,16.384,False,False,False,False,EX_succ_lp_e_rp_,True\n+FBA,10.000,10.000,2.523,2.523,0.000,16.384,False,False,False,False,FBA,False\n+FBP,0.000,0.000,-0.000,-0.000,0.000,16.384,False,False,False,False,FBP,False\n+FORt2,0.000,0.000,-0.000,-0.000,0.000,16.384,False,False,False,False,FORt2,False\n+FORti,0.000,0.000,-0.000,-0.000,0.000,16.384,False,False,False,False,FORti,False\n+FRD7,12.768,1000.000,0.000,0.000,0.000,16.384,False,False,False,False,FRD7,False\n+FRUpts2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,FRUpts2,False\n+FUM,-12.768,-12.768,17.833,17.833,0.000,16.384,False,True,False,False,FUM,False\n+FUMt2_2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,FUMt2_2,False\n+G6PDH2r,0.000,0.000,-4.960,-4.960,0.000,16.384,True,False,False,False,G6PDH2r,False\n+GAPD,20.000,20.000,3.976,3.976,0.000,16.384,False,False,False,False,GAPD,False\n+GLCpts,10.000,10.000,-0.000,-0.000,0.000,16.384,False,False,False,False,GLCpts,False\n+GLNS,0.000,0.000,-0.223,-0.223,0.000,16.384,True,False,False,False,GLNS,False\n+GLNabc,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLNabc,False\n+GLUDy,0.000,0.000,-4.542,-4.542,0.000,16.384,True,False,False,False,GLUDy,False\n+GLUN,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLUN,False\n+GLUSy,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLUSy,False\n+GLUt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLUt2r,False\n+GND,0.000,0.000,-4.960,-4.960,0.000,16.384,True,False,False,False,GND,False\n+H2Ot,-10.848,-10.848,-18.328,-18.328,0.000,16.384,False,False,False,False,H2Ot,False\n+ICDHyr,0.000,0.000,-6.007,-6.007,0.000,16.384,True,False,False,False,ICDHyr,False\n+ICL,3.616,3.616,3.616,3.616,0.000,16.384,False,False,False,False,ICL,False\n+LDH_D,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,LDH_D,False\n+MALS,3.616,3.616,3.616,3.616,0.000,16.384,False,False,False,False,MALS,False\n+MALt2_2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,MALt2_2,False\n+MDH,-9.153,-9.153,14.217,14.217,0.000,16.384,False,True,False,False,MDH,False\n+ME1,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ME1,False\n+ME2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ME2,False\n+NADH16,18.079,18.079,-20.455,-20.455,0.000,16.384,False,False,False,False,NADH16,False\n+NADTRHD,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,NADTRHD,False\n+NH4t,0.000,0.000,-4.765,-4.765,0.000,16.384,True,False,False,False,NH4t,False\n+O2t,2.655,2.655,-19.144,-19.144,0.000,16.384,False,False,False,False,O2t,False\n+PDH,7.232,7.232,-2.051,-2.051,0.000,16.384,False,False,False,False,PDH,False\n+PFK,10.000,10.000,2.523,2.523,0.000,16.384,False,False,False,False,PFK,False\n+PFL,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PFL,False\n+PGI,10.000,10.000,5.139,5.139,0.000,16.384,False,False,False,False,PGI,False\n+PGK,-20.000,-20.000,3.976,3.976,0.000,16.384,False,False,False,False,PGK,False\n+PGL,0.000,0.000,-4.960,-4.960,0.000,16.384,True,False,False,False,PGL,False\n+PGM,-20.000,-20.000,5.284,5.284,0.000,16.384,False,False,False,False,PGM,False\n+PIt2r,0.000,0.000,-3.215,-3.215,0.000,16.384,True,False,False,False,PIt2r,False\n+PPC,12.768,12.768,10.264,10.264,0.000,16.384,False,False,False,False,PPC,False\n+PPCK,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PPCK,False\n+PPS,2.768,2.768,2.768,2.768,0.000,16.384,False,False,False,False,PPS,False\n+PTAr,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PTAr,False\n+PYK,0.000,0.000,-1.758,-1.758,0.000,16.384,True,False,False,False,PYK,False\n+PYRt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PYRt2r,False\n+RPE,0.000,0.000,-2.678,-2.678,0.000,16.384,True,False,False,False,RPE,False\n+RPI,0.000,0.000,-2.282,-2.282,0.000,16.384,True,False,False,False,RPI,False\n+SUCCt2_2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,SUCCt2_2,False\n+SUCCt3,16.384,16.384,16.384,16.384,0.000,16.384,False,False,False,False,SUCCt3,False\n+SUCDi,0.000,987.232,0.000,0.000,0.000,16.384,False,False,False,False,SUCDi,False\n+SUCOAS,0.000,0.000,-5.064,-5.064,0.000,16.384,True,False,False,False,SUCOAS,False\n+TALA,0.000,0.000,-1.497,-1.497,0.000,16.384,True,False,False,False,TALA,False\n+THD2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,THD2,False\n+TKT1,0.000,0.000,-1.497,-1.497,0.000,16.384,True,False,False,False,TKT1,False\n+TKT2,0.000,0.000,-1.181,-1.181,0.000,16.384,True,False,False,False,TKT2,False\n+TPI,10.000,10.000,2.523,2.523,0.000,16.384,False,False,False,False,TPI,False\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/data/REFERENCE_DiffFVA2.csv",
"new_path": "tests/data/REFERENCE_DiffFVA2.csv",
"diff": "-,upper_bound,lower_bound,gaps,normalized_gaps,KO,flux_reversal,suddenly_essential,free_flux,excluded\n-ACALD,0.0,0.0,0.0,0.0,False,False,False,False,False\n-ACALDt,0.0,0.0,0.0,0.0,False,False,False,False,False\n-ACKr,0.0,0.0,0.0,0.0,False,False,False,False,False\n-ACONTa,3.615833333333285,3.615833333333285,0.0,0.0,False,False,False,False,False\n-ACONTb,3.615833333333285,3.615833333333285,0.0,0.0,False,False,False,False,False\n-ACt2r,0.0,0.0,0.0,0.0,False,False,False,False,False\n-ADK1,2.7683333333328806,2.7683333333328806,0.0,0.0,False,False,False,False,False\n-AKGDH,0.0,0.0,0.0,0.0,False,False,True,False,False\n-AKGt2r,0.0,0.0,0.0,0.0,False,False,False,False,False\n-ALCD2x,0.0,0.0,0.0,0.0,False,False,False,False,False\n-ATPM,8.39,8.39,0.0,0.0,False,False,False,False,False\n-ATPS4r,3.9266666666661836,3.9266666666661836,-17.2128536135224,-17.2128536135224,False,False,False,False,False\n-Biomass_Ecoli_core_N_lp_w_fsh_GAM_rp__Nmet2,0.0,0.0,-0.5771441593642541,-0.5771441593642541,True,False,True,False,True\n-CO2t,5.536666666666456,5.536666666666456,-11.890148048537977,-11.890148048537977,False,True,False,False,False\n-CS,3.615833333333285,3.615833333333285,0.0,0.0,False,False,False,False,False\n-CYTBD,5.310833333332994,5.310833333332994,-17.46939814497747,-17.46939814497747,False,False,False,False,False\n-D_LACt2,0.0,0.0,0.0,0.0,False,False,False,False,False\n-ENO,20.0,20.0,2.397629981246922,2.397629981246922,False,False,False,False,False\n-ETOHt2r,0.0,0.0,0.0,0.0,False,False,False,False,False\n-EX_succ_lp_e_rp_,16.38416666666667,16.38416666666667,10.725242819985578,10.725242819985578,False,False,False,False,True\n-FBA,10.0,10.0,0.5740852953196232,0.5740852953196232,False,False,False,False,False\n-FBP,0.0,0.0,0.0,0.0,False,False,True,False,False\n-FORt2,0.0,0.0,0.0,0.0,False,False,True,False,False\n-FORti,0.0,0.0,0.0,0.0,False,False,True,False,False\n-FRD7,1000.0,12.768333333333338,0.0,0.0,False,False,False,False,False\n-FRUpts2,0.0,0.0,0.0,0.0,False,False,True,False,False\n-FUM,-12.76833333333343,-12.76833333333343,8.387799982988781,8.387799982988781,False,False,False,False,False\n-FUMt2_2,0.0,0.0,0.0,0.0,False,False,True,False,False\n-G6PDH2r,0.0,0.0,0.0,0.0,False,False,True,False,False\n-GAPD,20.0,20.0,1.5342223188379975,1.5342223188379975,False,False,False,False,False\n-GLCpts,10.0,10.0,0.0,0.0,False,False,False,False,False\n-GLNS,0.0,0.0,-0.14757576154943977,-0.14757576154943977,True,False,True,False,False\n-GLNabc,0.0,0.0,0.0,0.0,False,False,True,False,False\n-GLUDy,0.0,0.0,0.0,0.0,True,False,False,False,False\n-GLUN,0.0,0.0,0.0,0.0,False,False,True,False,False\n-GLUSy,0.0,0.0,0.0,0.0,False,False,True,False,False\n-GLUt2r,0.0,0.0,0.0,0.0,False,False,False,False,False\n-GND,0.0,0.0,0.0,0.0,False,False,True,False,False\n-H2Ot,-10.847500000000203,-10.847500000000203,-1.710130296344282,-1.710130296344282,False,False,False,False,False\n-ICDHyr,0.0,0.0,-0.6226808335380936,-0.6226808335380936,True,False,True,False,False\n-ICL,3.615833333333285,3.615833333333285,0.0,0.0,False,False,False,False,False\n-LDH_D,0.0,0.0,0.0,0.0,False,False,False,False,False\n-MALS,3.615833333333285,3.615833333333285,0.0,0.0,False,False,False,False,False\n-MALt2_2,0.0,0.0,0.0,0.0,False,False,True,False,False\n-MDH,-9.152500000000146,-9.152500000000146,0.0,0.0,False,False,False,False,False\n-ME1,0.0,0.0,0.0,0.0,False,False,True,False,False\n-ME2,0.0,0.0,0.0,0.0,False,False,True,False,False\n-NADH16,18.079166666666424,18.079166666666424,-5.8503756045514095,-5.8503756045514095,False,False,False,False,False\n-NADTRHD,0.0,0.0,0.0,0.0,False,False,True,False,False\n-NH4t,0.0,0.0,-3.1470516721814046,-3.1470516721814046,True,False,True,False,False\n-O2t,2.655416666666497,2.655416666666497,-8.73469907248874,-8.73469907248874,False,False,False,False,False\n-PDH,7.23166666666657,7.23166666666657,0.0,0.0,False,False,False,False,False\n-PFK,9.99999999999945,9.99999999999945,0.0,0.0,False,False,False,False,False\n-PFL,0.0,0.0,0.0,0.0,False,False,True,False,False\n-PGI,10.0,10.0,0.11831455266967161,0.11831455266967161,False,False,False,False,False\n-PGK,-20.00000000000017,-20.00000000000017,1.534222318838168,1.534222318838168,False,False,False,False,False\n-PGL,0.0,0.0,0.0,0.0,False,False,True,False,False\n-PGM,-20.00000000000017,-20.00000000000017,2.3976299812470927,2.3976299812470927,False,False,False,False,False\n-PIt2r,0.0,0.0,-2.1231402190532833,-2.1231402190532833,True,False,True,False,False\n-PPC,12.76833333333343,12.76833333333343,0.0,0.0,False,False,False,False,False\n-PPCK,0.0,0.0,0.0,0.0,False,False,True,False,False\n-PPS,2.7683333333328806,2.7683333333328806,0.0,0.0,False,False,False,False,False\n-PTAr,0.0,0.0,0.0,0.0,False,False,True,False,False\n-PYK,0.0,0.0,0.0,0.0,False,False,True,False,False\n-PYRt2r,0.0,0.0,0.0,0.0,False,False,False,False,False\n-RPE,0.0,0.0,0.0,0.0,True,False,False,False,False\n-RPI,0.0,0.0,-0.41485122175102584,-0.41485122175102584,True,False,False,False,False\n-SUCCt2_2,0.0,0.0,0.0,0.0,False,False,True,False,False\n-SUCCt3,16.38416666666588,16.38416666666588,0.0,0.0,False,False,False,False,False\n-SUCDi,987.2316666666666,0.0,0.0,0.0,False,False,False,False,False\n-SUCOAS,0.0,0.0,0.0,0.0,False,False,False,False,False\n-TALA,0.0,0.0,0.0,0.0,True,False,False,False,False\n-THD2,0.0,0.0,0.0,0.0,False,False,True,False,False\n-TKT1,0.0,0.0,0.0,0.0,True,False,False,False,False\n-TKT2,0.0,0.0,0.0,0.0,True,False,False,False,False\n-TPI,10.0,10.0,0.5740852953196232,0.5740852953196232,False,False,False,False,False\n+,lower_bound,upper_bound,gaps,normalized_gaps,biomass,production,KO,flux_reversal,suddenly_essential,free_flux,reaction,excluded\n+ACALD,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACALD,False\n+ACALDt,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACALDt,False\n+ACKr,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACKr,False\n+ACONTa,3.616,3.616,-2.141,-2.141,0.000,16.384,False,False,False,False,ACONTa,False\n+ACONTb,3.616,3.616,-2.141,-2.141,0.000,16.384,False,False,False,False,ACONTb,False\n+ACt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACt2r,False\n+ADK1,2.768,2.768,2.768,2.768,0.000,16.384,False,False,False,False,ADK1,False\n+AKGDH,0.000,0.000,-4.926,-4.926,0.000,16.384,True,False,False,False,AKGDH,False\n+AKGt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,AKGt2r,False\n+ALCD2x,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ALCD2x,False\n+ATPM,8.390,8.390,0.000,0.000,0.000,16.384,False,False,False,False,ATPM,False\n+ATPS4r,3.927,3.927,-36.219,-36.219,0.000,16.384,False,False,False,False,ATPS4r,False\n+Biomass_Ecoli_core_N_lp_w_fsh_GAM_rp__Nmet2,0.000,0.000,-0.770,-0.770,0.000,16.384,True,False,False,False,Biomass_Ecoli_core_N_lp_w_fsh_GAM_rp__Nmet2,True\n+CO2t,5.537,5.537,-24.789,-24.789,0.000,16.384,False,True,False,False,CO2t,False\n+CS,3.616,3.616,-2.141,-2.141,0.000,16.384,False,False,False,False,CS,False\n+CYTBD,5.311,5.311,-33.415,-33.415,0.000,16.384,False,False,False,False,CYTBD,False\n+D_LACt2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,D_LACt2,False\n+ENO,20.000,20.000,4.575,4.575,0.000,16.384,False,False,False,False,ENO,False\n+ETOHt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ETOHt2r,False\n+EX_succ_lp_e_rp_,16.384,16.384,14.384,14.384,0.000,16.384,False,False,False,False,EX_succ_lp_e_rp_,True\n+FBA,10.000,10.000,2.143,2.143,0.000,16.384,False,False,False,False,FBA,False\n+FBP,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,FBP,False\n+FORt2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,FORt2,False\n+FORti,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,FORti,False\n+FRD7,12.768,1000.000,0.000,0.000,0.000,16.384,False,False,False,False,FRD7,False\n+FRUpts2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,FRUpts2,False\n+FUM,-12.768,-12.768,15.695,15.695,0.000,16.384,False,True,False,False,FUM,False\n+FUMt2_2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,FUMt2_2,False\n+G6PDH2r,0.000,0.000,-4.134,-4.134,0.000,16.384,True,False,False,False,G6PDH2r,False\n+GAPD,20.000,20.000,3.424,3.424,0.000,16.384,False,False,False,False,GAPD,False\n+GLCpts,10.000,10.000,0.000,0.000,0.000,16.384,False,False,False,False,GLCpts,False\n+GLNS,0.000,0.000,-0.197,-0.197,0.000,16.384,True,False,False,False,GLNS,False\n+GLNabc,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLNabc,False\n+GLUDy,0.000,0.000,-3.999,-3.999,0.000,16.384,True,False,False,False,GLUDy,False\n+GLUN,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLUN,False\n+GLUSy,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLUSy,False\n+GLUt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLUt2r,False\n+GND,0.000,0.000,-4.134,-4.134,0.000,16.384,True,False,False,False,GND,False\n+H2Ot,-10.848,-10.848,-16.010,-16.010,0.000,16.384,False,False,False,False,H2Ot,False\n+ICDHyr,0.000,0.000,-5.757,-5.757,0.000,16.384,True,False,False,False,ICDHyr,False\n+ICL,3.616,3.616,3.616,3.616,0.000,16.384,False,False,False,False,ICL,False\n+LDH_D,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,LDH_D,False\n+MALS,3.616,3.616,3.616,3.616,0.000,16.384,False,False,False,False,MALS,False\n+MALt2_2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,MALt2_2,False\n+MDH,-9.153,-9.153,12.079,12.079,0.000,16.384,False,True,False,False,MDH,False\n+ME1,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ME1,False\n+ME2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ME2,False\n+NADH16,18.079,18.079,-17.720,-17.720,0.000,16.384,False,False,False,False,NADH16,False\n+NADTRHD,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,NADTRHD,False\n+NH4t,0.000,0.000,-4.196,-4.196,0.000,16.384,True,False,False,False,NH4t,False\n+O2t,2.655,2.655,-16.707,-16.707,0.000,16.384,False,False,False,False,O2t,False\n+PDH,7.232,7.232,-1.409,-1.409,0.000,16.384,False,False,False,False,PDH,False\n+PFK,10.000,10.000,2.143,2.143,0.000,16.384,False,False,False,False,PFK,False\n+PFL,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PFL,False\n+PGI,10.000,10.000,4.292,4.292,0.000,16.384,False,False,False,False,PGI,False\n+PGK,-20.000,-20.000,3.424,3.424,0.000,16.384,False,False,False,False,PGK,False\n+PGL,0.000,0.000,-4.134,-4.134,0.000,16.384,True,False,False,False,PGL,False\n+PGM,-20.000,-20.000,4.575,4.575,0.000,16.384,False,False,False,False,PGM,False\n+PIt2r,0.000,0.000,-2.831,-2.831,0.000,16.384,True,False,False,False,PIt2r,False\n+PPC,12.768,12.768,8.563,8.563,0.000,16.384,False,False,False,False,PPC,False\n+PPCK,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PPCK,False\n+PPS,2.768,2.768,2.768,2.768,0.000,16.384,False,False,False,False,PPS,False\n+PTAr,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PTAr,False\n+PYK,0.000,0.000,-0.821,-0.821,0.000,16.384,True,False,False,False,PYK,False\n+PYRt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PYRt2r,False\n+RPE,0.000,0.000,-2.203,-2.203,0.000,16.384,True,False,False,False,RPE,False\n+RPI,0.000,0.000,-1.931,-1.931,0.000,16.384,True,False,False,False,RPI,False\n+SUCCt2_2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,SUCCt2_2,False\n+SUCCt3,16.384,16.384,14.384,14.384,0.000,16.384,False,False,False,False,SUCCt3,False\n+SUCDi,0.000,987.232,0.000,0.000,0.000,16.384,False,False,False,False,SUCDi,False\n+SUCOAS,0.000,0.000,-4.926,-4.926,0.000,16.384,True,False,False,False,SUCOAS,False\n+TALA,0.000,0.000,-1.240,-1.240,0.000,16.384,True,False,False,False,TALA,False\n+THD2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,THD2,False\n+TKT1,0.000,0.000,-1.240,-1.240,0.000,16.384,True,False,False,False,TKT1,False\n+TKT2,0.000,0.000,-0.963,-0.963,0.000,16.384,True,False,False,False,TKT2,False\n+TPI,10.000,10.000,2.143,2.143,0.000,16.384,False,False,False,False,TPI,False\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/data/REFERENCE_PPP_o2_EcoliCore.csv",
"new_path": "tests/data/REFERENCE_PPP_o2_EcoliCore.csv",
"diff": ",EX_o2_LPAREN_e_RPAREN_,objective_lower_bound,objective_upper_bound,c_yield_lower_bound,c_yield_upper_bound,mass_yield_lower_bound,mass_yield_upper_bound\n-0,-60.000,0.000,0.000,0.000,0.000,,\n+0,-60.000,0.000,-0.000,0.000,0.000,,\n1,-56.842,0.000,0.072,0.000,1.310,,\n2,-53.684,0.000,0.144,0.000,2.620,,\n3,-50.526,0.000,0.217,0.000,3.930,,\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/data/REFERENCE_PPP_o2_EcoliCore_ac.csv",
"new_path": "tests/data/REFERENCE_PPP_o2_EcoliCore_ac.csv",
"diff": ",EX_o2_LPAREN_e_RPAREN_,objective_lower_bound,objective_upper_bound,c_yield_lower_bound,c_yield_upper_bound,mass_yield_lower_bound,mass_yield_upper_bound\n-0,-60.000,0.000,-0.000,0.000,0.000,0.000,0.000\n+0,-60.000,0.000,0.000,0.000,0.000,0.000,0.000\n1,-56.842,0.000,1.579,0.000,0.053,0.000,0.052\n2,-53.684,0.000,3.158,0.000,0.105,0.000,0.103\n3,-50.526,0.000,4.737,0.000,0.158,0.000,0.155\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/data/REFERENCE_PPP_o2_glc_EcoliCore.csv",
"new_path": "tests/data/REFERENCE_PPP_o2_glc_EcoliCore.csv",
"diff": ",EX_o2_LPAREN_e_RPAREN_,EX_glc_LPAREN_e_RPAREN_,objective_lower_bound,objective_upper_bound,c_yield_lower_bound,c_yield_upper_bound,mass_yield_lower_bound,mass_yield_upper_bound\n-0,-60.000,-10.000,0.000,0.000,0.000,0.000,,\n+0,-60.000,-10.000,0.000,-0.000,0.000,0.000,,\n1,-60.000,-9.499,,,,,,\n2,-60.000,-8.998,,,,,,\n3,-60.000,-8.497,,,,,,\n"
},
{
"change_type": "DELETE",
"old_path": "tests/data/make-data-sets.py",
"new_path": null,
"diff": "-from cameo import load_model\n-from cameo.flux_analysis import phenotypic_phase_plane\n-import os\n-\n-TESTDIR = os.path.dirname(__file__)\n-CORE_MODEL = load_model(os.path.join(TESTDIR, 'EcoliCore.xml'), sanitize=False)\n-\n-model = CORE_MODEL.copy()\n-model.solver = 'glpk'\n-ppp = phenotypic_phase_plane(model, ['EX_o2_LPAREN_e_RPAREN_'])\n-ppp.data_frame.to_csv(os.path.join(TESTDIR, 'REFERENCE_PPP_o2_EcoliCore.csv'), float_format='%.3f')\n-\n-model = CORE_MODEL.copy()\n-model.solver = 'glpk'\n-ppp2d = phenotypic_phase_plane(model, ['EX_o2_LPAREN_e_RPAREN_', 'EX_glc_LPAREN_e_RPAREN_'])\n-ppp2d.data_frame.to_csv(os.path.join(TESTDIR, 'REFERENCE_PPP_o2_glc_EcoliCore.csv'), float_format='%.3f')\n-\n-model = CORE_MODEL.copy()\n-model.solver = 'glpk'\n-objective = model.add_boundary(model.metabolites.ac_c, type='demand')\n-model.objective = objective\n-ppp = phenotypic_phase_plane(model, ['EX_o2_LPAREN_e_RPAREN_'])\n-ppp.data_frame.to_csv(os.path.join(TESTDIR, 'REFERENCE_PPP_o2_EcoliCore_ac.csv'), float_format='%.3f')\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "tests/data/make_data_sets.py",
"diff": "+from os.path import dirname, join\n+\n+import cobra\n+from cobra.io import read_sbml_model\n+\n+from cameo import load_model\n+from cameo.io import sanitize_ids\n+from cameo.flux_analysis import phenotypic_phase_plane\n+from cameo.strain_design.deterministic.flux_variability_based import DifferentialFVA\n+\n+\n+config = cobra.Configuration()\n+TESTDIR = dirname(__file__)\n+\n+\n+def generate_ppp(model):\n+ tmp = model.copy()\n+ ppp = phenotypic_phase_plane(tmp, [\"EX_o2_LPAREN_e_RPAREN_\"])\n+ ppp.data_frame.to_csv(\n+ join(TESTDIR, \"REFERENCE_PPP_o2_EcoliCore.csv\"), float_format=\"%.3f\"\n+ )\n+\n+ tmp = model.copy()\n+ ppp2d = phenotypic_phase_plane(\n+ tmp, [\"EX_o2_LPAREN_e_RPAREN_\", \"EX_glc_LPAREN_e_RPAREN_\"]\n+ )\n+ ppp2d.data_frame.to_csv(\n+ join(TESTDIR, \"REFERENCE_PPP_o2_glc_EcoliCore.csv\"), float_format=\"%.3f\"\n+ )\n+\n+ tmp = model.copy()\n+ objective = tmp.add_boundary(tmp.metabolites.ac_c, type=\"demand\")\n+ tmp.objective = objective\n+ ppp = phenotypic_phase_plane(tmp, [\"EX_o2_LPAREN_e_RPAREN_\"])\n+ ppp.data_frame.to_csv(\n+ join(TESTDIR, \"REFERENCE_PPP_o2_EcoliCore_ac.csv\"), float_format=\"%.3f\"\n+ )\n+\n+\n+def generate_diff_fva(model):\n+ diff_fva = DifferentialFVA(model, model.reactions.EX_succ_lp_e_rp_, points=5)\n+ result = diff_fva.run()\n+ df = result.nth_panel(0)\n+ df.index.name = None\n+ df.to_csv(join(TESTDIR, \"REFERENCE_DiffFVA1.csv\"), float_format=\"%.3f\")\n+\n+ reference_model = model.copy()\n+ biomass_rxn = reference_model.reactions.Biomass_Ecoli_core_N_lp_w_fsh_GAM_rp__Nmet2\n+ biomass_rxn.lower_bound = 0.3\n+ target = reference_model.reactions.EX_succ_lp_e_rp_\n+ target.lower_bound = 2\n+ result = DifferentialFVA(\n+ model, target, reference_model=reference_model, points=5\n+ ).run()\n+ df = result.nth_panel(0)\n+ df.index.name = None\n+ df.to_csv(join(TESTDIR, \"REFERENCE_DiffFVA2.csv\"), float_format=\"%.3f\")\n+\n+\n+if __name__ == \"__main__\":\n+ core_model = load_model(join(TESTDIR, \"EcoliCore.xml\"), sanitize=False)\n+ core_model.solver = \"glpk\"\n+ generate_ppp(core_model)\n+ config.solver = \"glpk\"\n+ core_model = read_sbml_model(join(TESTDIR, \"EcoliCore.xml\"))\n+ sanitize_ids(core_model)\n+ generate_diff_fva(core_model)\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | chore: update test data generation script |
89,734 | 24.06.2019 14:22:51 | -7,200 | d69038b5cc2feebff9b220c1537a16c9dc4c5aa1 | tests: fix differential FVA comparison | [
{
"change_type": "MODIFY",
"old_path": "tests/conftest.py",
"new_path": "tests/conftest.py",
"diff": "@@ -19,7 +19,9 @@ def data_directory():\[email protected](scope='session')\ndef model(data_directory):\n- return load_model(join(data_directory, 'EcoliCore.xml'))\n+ m = load_model(join(data_directory, 'EcoliCore.xml'))\n+ m.solver = \"glpk\"\n+ return m\[email protected](scope=\"session\")\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/test_strain_design_deterministic.py",
"new_path": "tests/test_strain_design_deterministic.py",
"diff": "@@ -68,9 +68,15 @@ class TestDifferentialFVA:\ndef test_minimal_input(self, diff_fva):\nresult = diff_fva.run()\nref_df = pandas.read_csv(os.path.join(TESTDIR, 'data/REFERENCE_DiffFVA1.csv'), index_col=0)\n+ ref_df.sort_index(inplace=True)\nthis_df = result.nth_panel(0)\nthis_df.index.name = None\n- pandas.util.testing.assert_frame_equal(this_df[ref_df.columns], ref_df)\n+ this_df.sort_index(inplace=True)\n+ pandas.util.testing.assert_frame_equal(\n+ this_df[ref_df.columns],\n+ ref_df,\n+ check_less_precise=2 # Number of digits for equality check.\n+ )\ndef test_apply_designs(self, model, diff_fva):\nresult = diff_fva.run()\n@@ -96,9 +102,15 @@ class TestDifferentialFVA:\ntarget.lower_bound = 2\nresult = DifferentialFVA(model, target, reference_model=reference_model, points=5).run()\nref_df = pandas.read_csv(os.path.join(TESTDIR, 'data/REFERENCE_DiffFVA2.csv'), index_col=0)\n+ ref_df.sort_index(inplace=True)\nthis_df = result.nth_panel(0)\nthis_df.index.name = None\n- pandas.util.testing.assert_frame_equal(this_df[ref_df.columns], ref_df)\n+ this_df.sort_index(inplace=True)\n+ pandas.util.testing.assert_frame_equal(\n+ this_df[ref_df.columns],\n+ ref_df,\n+ check_less_precise=2 # Number of digits for equality check.\n+ )\[email protected]('cplex' not in solvers, reason=\"No cplex interface available\")\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | tests: fix differential FVA comparison |
89,734 | 25.06.2019 11:16:35 | -7,200 | eec6d4f9173c6db98d7616023a1baa9730c50507 | tests: catch the right error
`Infeasible` is the logical one but cobrapy only raises a general
`OptimizationError`. | [
{
"change_type": "MODIFY",
"old_path": "tests/test_strain_design_deterministic.py",
"new_path": "tests/test_strain_design_deterministic.py",
"diff": "@@ -21,10 +21,9 @@ import pytest\nfrom pandas import DataFrame\nfrom pandas.util.testing import assert_frame_equal\n-from cobra.exceptions import Infeasible\n+from cobra.exceptions import OptimizationError\nimport cameo\n-from cameo import fba\nfrom cameo.config import solvers\nfrom cameo.strain_design.deterministic.flux_variability_based import (FSEOF,\nDifferentialFVA,\n@@ -85,9 +84,9 @@ class TestDifferentialFVA:\nwith model:\nstrain_design.apply(model)\ntry:\n- solution = fba(model, objective=\"Biomass_Ecoli_core_N_lp_w_fsh_GAM_rp__Nmet2\")\n+ solution = model.optimize(raise_error=True)\nworks.append(solution[\"EX_succ_lp_e_rp_\"] > 1e-6 and solution.objective_value > 1e-6)\n- except Infeasible:\n+ except OptimizationError:\nworks.append(False)\nassert any(works)\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | tests: catch the right error
`Infeasible` is the logical one but cobrapy only raises a general
`OptimizationError`. |
89,734 | 25.06.2019 15:00:06 | -7,200 | 35e2e028f539395cdbd9aa7ead831d7887a59f06 | fix: set all solution within threshold to zero | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -322,6 +322,9 @@ class DifferentialFVA(StrainDesignMethod):\nremove_cycles=False,\nfraction_of_optimum=fraction_of_optimum\n).data_frame\n+ self.reference_flux_ranges[\n+ self.reference_flux_ranges.abs() < non_zero_flux_threshold\n+ ] = 0.0\nreference_intervals = self.reference_flux_ranges.loc[\nself.included_reactions,\n['lower_bound', 'upper_bound']\n@@ -378,6 +381,7 @@ class DifferentialFVA(StrainDesignMethod):\nsolutions = dict((tuple(point.iteritems()), fva_result) for (point, fva_result) in results)\nfor sol in six.itervalues(solutions):\n+ sol[sol.abs() < non_zero_flux_threshold] = 0.0\nintervals = sol.loc[\nself.included_reactions,\n['lower_bound', 'upper_bound']\n@@ -405,11 +409,6 @@ class DifferentialFVA(StrainDesignMethod):\nelse:\nsol['normalized_gaps'] = gaps\n- ref_upper_bound = self.reference_flux_ranges.upper_bound.apply(\n- lambda v: 0 if abs(v) < non_zero_flux_threshold else v)\n- ref_lower_bound = self.reference_flux_ranges.lower_bound.apply(\n- lambda v: 0 if abs(v) < non_zero_flux_threshold else v)\n-\n# Determine where the reference flux range overlaps with zero.\nzero_overlap_mask = numpy.asarray([\nself._interval_overlap(interval1, (0, 0)) > 0\n@@ -428,14 +427,14 @@ class DifferentialFVA(StrainDesignMethod):\ndf.loc[\n(df.lower_bound == 0) & (\ndf.upper_bound == 0) & (\n- ref_upper_bound != 0) & (\n- ref_lower_bound != 0),\n+ self.reference_flux_ranges.upper_bound != 0) & (\n+ self.reference_flux_ranges.lower_bound != 0),\n'KO'\n] = True\ndf.loc[\n- ((ref_upper_bound < 0) & (df.lower_bound > 0) | (\n- (ref_lower_bound > 0) & (df.upper_bound < 0))),\n+ ((self.reference_flux_ranges.upper_bound < 0) & (df.lower_bound > 0) | (\n+ (self.reference_flux_ranges.lower_bound > 0) & (df.upper_bound < 0))),\n'flux_reversal'\n] = True\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: set all solution within threshold to zero |
89,734 | 25.06.2019 15:03:15 | -7,200 | b2fecb76742352071eb2194bd210f22cf0806f8c | refactor: change knock-out condition to use overlap | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -427,8 +427,8 @@ class DifferentialFVA(StrainDesignMethod):\ndf.loc[\n(df.lower_bound == 0) & (\ndf.upper_bound == 0) & (\n- self.reference_flux_ranges.upper_bound != 0) & (\n- self.reference_flux_ranges.lower_bound != 0),\n+ ~zero_overlap_mask\n+ ),\n'KO'\n] = True\n@@ -447,7 +447,7 @@ class DifferentialFVA(StrainDesignMethod):\nis_reversible = numpy.asarray([\nself.design_space_model.reactions.get_by_id(i).reversibility\nfor i in df.index], dtype=bool)\n- not_reversible = numpy.logical_not(is_reversible)\n+ not_reversible = ~is_reversible\ndf.loc[\n((df.lower_bound == -1000) & (df.upper_bound == 1000) & is_reversible) | (\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | refactor: change knock-out condition to use overlap |
89,734 | 25.06.2019 16:17:46 | -7,200 | b969996ae4c431a133d6023cbbd29324fa68d2e3 | chore: re-generate data | [
{
"change_type": "MODIFY",
"old_path": "tests/data/REFERENCE_DiffFVA1.csv",
"new_path": "tests/data/REFERENCE_DiffFVA1.csv",
"diff": ",lower_bound,upper_bound,gaps,normalized_gaps,biomass,production,KO,flux_reversal,suddenly_essential,free_flux,reaction,excluded\n-ACALD,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACALD,False\n-ACALDt,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACALDt,False\n-ACKr,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACKr,False\n+ACALD,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ACALD,False\n+ACALDt,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ACALDt,False\n+ACKr,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ACKr,False\nACONTa,3.616,3.616,-2.391,-2.391,0.000,16.384,False,False,False,False,ACONTa,False\nACONTb,3.616,3.616,-2.391,-2.391,0.000,16.384,False,False,False,False,ACONTb,False\n-ACt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACt2r,False\n+ACt2r,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ACt2r,False\nADK1,2.768,2.768,2.768,2.768,0.000,16.384,False,False,False,False,ADK1,False\nAKGDH,0.000,0.000,-5.064,-5.064,0.000,16.384,True,False,False,False,AKGDH,False\n-AKGt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,AKGt2r,False\n-ALCD2x,0.000,0.000,-0.000,-0.000,0.000,16.384,False,False,False,False,ALCD2x,False\n+AKGt2r,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,AKGt2r,False\n+ALCD2x,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ALCD2x,False\nATPM,8.390,8.390,0.000,0.000,0.000,16.384,False,False,False,False,ATPM,False\nATPS4r,3.927,3.927,-41.587,-41.587,0.000,16.384,False,False,False,False,ATPS4r,False\nBiomass_Ecoli_core_N_lp_w_fsh_GAM_rp__Nmet2,0.000,0.000,-0.874,-0.874,0.000,16.384,True,False,False,False,Biomass_Ecoli_core_N_lp_w_fsh_GAM_rp__Nmet2,True\nCO2t,5.537,5.537,-28.346,-28.346,0.000,16.384,False,True,False,False,CO2t,False\nCS,3.616,3.616,-2.391,-2.391,0.000,16.384,False,False,False,False,CS,False\nCYTBD,5.311,5.311,-38.288,-38.288,0.000,16.384,False,False,False,False,CYTBD,False\n-D_LACt2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,D_LACt2,False\n+D_LACt2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,D_LACt2,False\nENO,20.000,20.000,5.284,5.284,0.000,16.384,False,False,False,False,ENO,False\n-ETOHt2r,0.000,0.000,-0.000,-0.000,0.000,16.384,False,False,False,False,ETOHt2r,False\n+ETOHt2r,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ETOHt2r,False\nEX_succ_lp_e_rp_,16.384,16.384,16.384,16.384,0.000,16.384,False,False,False,False,EX_succ_lp_e_rp_,True\nFBA,10.000,10.000,2.523,2.523,0.000,16.384,False,False,False,False,FBA,False\n-FBP,0.000,0.000,-0.000,-0.000,0.000,16.384,False,False,False,False,FBP,False\n-FORt2,0.000,0.000,-0.000,-0.000,0.000,16.384,False,False,False,False,FORt2,False\n-FORti,0.000,0.000,-0.000,-0.000,0.000,16.384,False,False,False,False,FORti,False\n+FBP,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,FBP,False\n+FORt2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,FORt2,False\n+FORti,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,FORti,False\nFRD7,12.768,1000.000,0.000,0.000,0.000,16.384,False,False,False,False,FRD7,False\n-FRUpts2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,FRUpts2,False\n+FRUpts2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,FRUpts2,False\nFUM,-12.768,-12.768,17.833,17.833,0.000,16.384,False,True,False,False,FUM,False\n-FUMt2_2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,FUMt2_2,False\n+FUMt2_2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,FUMt2_2,False\nG6PDH2r,0.000,0.000,-4.960,-4.960,0.000,16.384,True,False,False,False,G6PDH2r,False\nGAPD,20.000,20.000,3.976,3.976,0.000,16.384,False,False,False,False,GAPD,False\nGLCpts,10.000,10.000,-0.000,-0.000,0.000,16.384,False,False,False,False,GLCpts,False\nGLNS,0.000,0.000,-0.223,-0.223,0.000,16.384,True,False,False,False,GLNS,False\n-GLNabc,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLNabc,False\n+GLNabc,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,GLNabc,False\nGLUDy,0.000,0.000,-4.542,-4.542,0.000,16.384,True,False,False,False,GLUDy,False\n-GLUN,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLUN,False\n-GLUSy,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLUSy,False\n-GLUt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLUt2r,False\n+GLUN,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,GLUN,False\n+GLUSy,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,GLUSy,False\n+GLUt2r,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,GLUt2r,False\nGND,0.000,0.000,-4.960,-4.960,0.000,16.384,True,False,False,False,GND,False\nH2Ot,-10.848,-10.848,-18.328,-18.328,0.000,16.384,False,False,False,False,H2Ot,False\nICDHyr,0.000,0.000,-6.007,-6.007,0.000,16.384,True,False,False,False,ICDHyr,False\nICL,3.616,3.616,3.616,3.616,0.000,16.384,False,False,False,False,ICL,False\n-LDH_D,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,LDH_D,False\n+LDH_D,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,LDH_D,False\nMALS,3.616,3.616,3.616,3.616,0.000,16.384,False,False,False,False,MALS,False\n-MALt2_2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,MALt2_2,False\n+MALt2_2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,MALt2_2,False\nMDH,-9.153,-9.153,14.217,14.217,0.000,16.384,False,True,False,False,MDH,False\n-ME1,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ME1,False\n-ME2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ME2,False\n+ME1,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ME1,False\n+ME2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ME2,False\nNADH16,18.079,18.079,-20.455,-20.455,0.000,16.384,False,False,False,False,NADH16,False\n-NADTRHD,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,NADTRHD,False\n+NADTRHD,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,NADTRHD,False\nNH4t,0.000,0.000,-4.765,-4.765,0.000,16.384,True,False,False,False,NH4t,False\nO2t,2.655,2.655,-19.144,-19.144,0.000,16.384,False,False,False,False,O2t,False\nPDH,7.232,7.232,-2.051,-2.051,0.000,16.384,False,False,False,False,PDH,False\nPFK,10.000,10.000,2.523,2.523,0.000,16.384,False,False,False,False,PFK,False\n-PFL,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PFL,False\n+PFL,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,PFL,False\nPGI,10.000,10.000,5.139,5.139,0.000,16.384,False,False,False,False,PGI,False\nPGK,-20.000,-20.000,3.976,3.976,0.000,16.384,False,False,False,False,PGK,False\nPGL,0.000,0.000,-4.960,-4.960,0.000,16.384,True,False,False,False,PGL,False\nPGM,-20.000,-20.000,5.284,5.284,0.000,16.384,False,False,False,False,PGM,False\nPIt2r,0.000,0.000,-3.215,-3.215,0.000,16.384,True,False,False,False,PIt2r,False\nPPC,12.768,12.768,10.264,10.264,0.000,16.384,False,False,False,False,PPC,False\n-PPCK,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PPCK,False\n+PPCK,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,PPCK,False\nPPS,2.768,2.768,2.768,2.768,0.000,16.384,False,False,False,False,PPS,False\n-PTAr,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PTAr,False\n+PTAr,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,PTAr,False\nPYK,0.000,0.000,-1.758,-1.758,0.000,16.384,True,False,False,False,PYK,False\n-PYRt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PYRt2r,False\n+PYRt2r,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,PYRt2r,False\nRPE,0.000,0.000,-2.678,-2.678,0.000,16.384,True,False,False,False,RPE,False\nRPI,0.000,0.000,-2.282,-2.282,0.000,16.384,True,False,False,False,RPI,False\n-SUCCt2_2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,SUCCt2_2,False\n+SUCCt2_2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,SUCCt2_2,False\nSUCCt3,16.384,16.384,16.384,16.384,0.000,16.384,False,False,False,False,SUCCt3,False\nSUCDi,0.000,987.232,0.000,0.000,0.000,16.384,False,False,False,False,SUCDi,False\nSUCOAS,0.000,0.000,-5.064,-5.064,0.000,16.384,True,False,False,False,SUCOAS,False\nTALA,0.000,0.000,-1.497,-1.497,0.000,16.384,True,False,False,False,TALA,False\n-THD2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,THD2,False\n+THD2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,THD2,False\nTKT1,0.000,0.000,-1.497,-1.497,0.000,16.384,True,False,False,False,TKT1,False\nTKT2,0.000,0.000,-1.181,-1.181,0.000,16.384,True,False,False,False,TKT2,False\nTPI,10.000,10.000,2.523,2.523,0.000,16.384,False,False,False,False,TPI,False\n"
},
{
"change_type": "MODIFY",
"old_path": "tests/data/REFERENCE_DiffFVA2.csv",
"new_path": "tests/data/REFERENCE_DiffFVA2.csv",
"diff": ",lower_bound,upper_bound,gaps,normalized_gaps,biomass,production,KO,flux_reversal,suddenly_essential,free_flux,reaction,excluded\n-ACALD,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACALD,False\n-ACALDt,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACALDt,False\n-ACKr,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACKr,False\n+ACALD,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ACALD,False\n+ACALDt,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ACALDt,False\n+ACKr,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ACKr,False\nACONTa,3.616,3.616,-2.141,-2.141,0.000,16.384,False,False,False,False,ACONTa,False\nACONTb,3.616,3.616,-2.141,-2.141,0.000,16.384,False,False,False,False,ACONTb,False\n-ACt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ACt2r,False\n+ACt2r,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ACt2r,False\nADK1,2.768,2.768,2.768,2.768,0.000,16.384,False,False,False,False,ADK1,False\nAKGDH,0.000,0.000,-4.926,-4.926,0.000,16.384,True,False,False,False,AKGDH,False\n-AKGt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,AKGt2r,False\n-ALCD2x,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ALCD2x,False\n+AKGt2r,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,AKGt2r,False\n+ALCD2x,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ALCD2x,False\nATPM,8.390,8.390,0.000,0.000,0.000,16.384,False,False,False,False,ATPM,False\nATPS4r,3.927,3.927,-36.219,-36.219,0.000,16.384,False,False,False,False,ATPS4r,False\nBiomass_Ecoli_core_N_lp_w_fsh_GAM_rp__Nmet2,0.000,0.000,-0.770,-0.770,0.000,16.384,True,False,False,False,Biomass_Ecoli_core_N_lp_w_fsh_GAM_rp__Nmet2,True\nCO2t,5.537,5.537,-24.789,-24.789,0.000,16.384,False,True,False,False,CO2t,False\nCS,3.616,3.616,-2.141,-2.141,0.000,16.384,False,False,False,False,CS,False\nCYTBD,5.311,5.311,-33.415,-33.415,0.000,16.384,False,False,False,False,CYTBD,False\n-D_LACt2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,D_LACt2,False\n+D_LACt2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,D_LACt2,False\nENO,20.000,20.000,4.575,4.575,0.000,16.384,False,False,False,False,ENO,False\n-ETOHt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ETOHt2r,False\n+ETOHt2r,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ETOHt2r,False\nEX_succ_lp_e_rp_,16.384,16.384,14.384,14.384,0.000,16.384,False,False,False,False,EX_succ_lp_e_rp_,True\nFBA,10.000,10.000,2.143,2.143,0.000,16.384,False,False,False,False,FBA,False\n-FBP,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,FBP,False\n-FORt2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,FORt2,False\n-FORti,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,FORti,False\n+FBP,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,FBP,False\n+FORt2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,FORt2,False\n+FORti,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,FORti,False\nFRD7,12.768,1000.000,0.000,0.000,0.000,16.384,False,False,False,False,FRD7,False\n-FRUpts2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,FRUpts2,False\n+FRUpts2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,FRUpts2,False\nFUM,-12.768,-12.768,15.695,15.695,0.000,16.384,False,True,False,False,FUM,False\n-FUMt2_2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,FUMt2_2,False\n+FUMt2_2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,FUMt2_2,False\nG6PDH2r,0.000,0.000,-4.134,-4.134,0.000,16.384,True,False,False,False,G6PDH2r,False\nGAPD,20.000,20.000,3.424,3.424,0.000,16.384,False,False,False,False,GAPD,False\nGLCpts,10.000,10.000,0.000,0.000,0.000,16.384,False,False,False,False,GLCpts,False\nGLNS,0.000,0.000,-0.197,-0.197,0.000,16.384,True,False,False,False,GLNS,False\n-GLNabc,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLNabc,False\n+GLNabc,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,GLNabc,False\nGLUDy,0.000,0.000,-3.999,-3.999,0.000,16.384,True,False,False,False,GLUDy,False\n-GLUN,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLUN,False\n-GLUSy,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLUSy,False\n-GLUt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,GLUt2r,False\n+GLUN,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,GLUN,False\n+GLUSy,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,GLUSy,False\n+GLUt2r,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,GLUt2r,False\nGND,0.000,0.000,-4.134,-4.134,0.000,16.384,True,False,False,False,GND,False\nH2Ot,-10.848,-10.848,-16.010,-16.010,0.000,16.384,False,False,False,False,H2Ot,False\nICDHyr,0.000,0.000,-5.757,-5.757,0.000,16.384,True,False,False,False,ICDHyr,False\nICL,3.616,3.616,3.616,3.616,0.000,16.384,False,False,False,False,ICL,False\n-LDH_D,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,LDH_D,False\n+LDH_D,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,LDH_D,False\nMALS,3.616,3.616,3.616,3.616,0.000,16.384,False,False,False,False,MALS,False\n-MALt2_2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,MALt2_2,False\n+MALt2_2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,MALt2_2,False\nMDH,-9.153,-9.153,12.079,12.079,0.000,16.384,False,True,False,False,MDH,False\n-ME1,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ME1,False\n-ME2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,ME2,False\n+ME1,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ME1,False\n+ME2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,ME2,False\nNADH16,18.079,18.079,-17.720,-17.720,0.000,16.384,False,False,False,False,NADH16,False\n-NADTRHD,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,NADTRHD,False\n+NADTRHD,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,NADTRHD,False\nNH4t,0.000,0.000,-4.196,-4.196,0.000,16.384,True,False,False,False,NH4t,False\nO2t,2.655,2.655,-16.707,-16.707,0.000,16.384,False,False,False,False,O2t,False\nPDH,7.232,7.232,-1.409,-1.409,0.000,16.384,False,False,False,False,PDH,False\nPFK,10.000,10.000,2.143,2.143,0.000,16.384,False,False,False,False,PFK,False\n-PFL,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PFL,False\n+PFL,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,PFL,False\nPGI,10.000,10.000,4.292,4.292,0.000,16.384,False,False,False,False,PGI,False\nPGK,-20.000,-20.000,3.424,3.424,0.000,16.384,False,False,False,False,PGK,False\nPGL,0.000,0.000,-4.134,-4.134,0.000,16.384,True,False,False,False,PGL,False\nPGM,-20.000,-20.000,4.575,4.575,0.000,16.384,False,False,False,False,PGM,False\nPIt2r,0.000,0.000,-2.831,-2.831,0.000,16.384,True,False,False,False,PIt2r,False\nPPC,12.768,12.768,8.563,8.563,0.000,16.384,False,False,False,False,PPC,False\n-PPCK,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PPCK,False\n+PPCK,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,PPCK,False\nPPS,2.768,2.768,2.768,2.768,0.000,16.384,False,False,False,False,PPS,False\n-PTAr,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PTAr,False\n+PTAr,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,PTAr,False\nPYK,0.000,0.000,-0.821,-0.821,0.000,16.384,True,False,False,False,PYK,False\n-PYRt2r,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,PYRt2r,False\n+PYRt2r,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,PYRt2r,False\nRPE,0.000,0.000,-2.203,-2.203,0.000,16.384,True,False,False,False,RPE,False\nRPI,0.000,0.000,-1.931,-1.931,0.000,16.384,True,False,False,False,RPI,False\n-SUCCt2_2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,SUCCt2_2,False\n+SUCCt2_2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,SUCCt2_2,False\nSUCCt3,16.384,16.384,14.384,14.384,0.000,16.384,False,False,False,False,SUCCt3,False\nSUCDi,0.000,987.232,0.000,0.000,0.000,16.384,False,False,False,False,SUCDi,False\nSUCOAS,0.000,0.000,-4.926,-4.926,0.000,16.384,True,False,False,False,SUCOAS,False\nTALA,0.000,0.000,-1.240,-1.240,0.000,16.384,True,False,False,False,TALA,False\n-THD2,0.000,0.000,0.000,0.000,0.000,16.384,False,False,False,False,THD2,False\n+THD2,0.000,0.000,0.000,0.000,0.000,16.384,True,False,False,False,THD2,False\nTKT1,0.000,0.000,-1.240,-1.240,0.000,16.384,True,False,False,False,TKT1,False\nTKT2,0.000,0.000,-0.963,-0.963,0.000,16.384,True,False,False,False,TKT2,False\nTPI,10.000,10.000,2.143,2.143,0.000,16.384,False,False,False,False,TPI,False\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | chore: re-generate data |
89,734 | 26.06.2019 20:40:07 | -7,200 | 0b114260c05628c8b7d6ac0b200b9f015ee6187d | fix: upgrade groupby | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -480,6 +480,9 @@ class DifferentialFVAResult(StrainDesignMethodResult):\nself.reference_fva = reference_fva\nself.reference_fluxes = reference_fluxes\nself.solutions = solutions\n+ self.groups = self.solutions.groupby(\n+ ('biomass', 'production'), as_index=False, sort=False\n+ )\n@classmethod\ndef _closest_bound(cls, ref_interval, row_interval):\n@@ -563,7 +566,7 @@ class DifferentialFVAResult(StrainDesignMethodResult):\nA list of cameo.core.strain_design.StrainDesign for each DataFrame in solutions.\n\"\"\"\ndesigns = []\n- for _, solution in solutions.groupby(('biomass', 'production')):\n+ for _, solution in solutions.groupby(('biomass', 'production'), as_index=False, sort=False):\ntargets = []\nrelevant_targets = solution.loc[\n(numpy.abs(solution['normalized_gaps']) > non_zero_flux_threshold) & (\n@@ -603,10 +606,7 @@ class DifferentialFVAResult(StrainDesignMethodResult):\nreturn designs\ndef __getitem__(self, item):\n- columns = [\"lower_bound\", \"upper_bound\", \"gaps\", \"normalized_gaps\", \"KO\", \"flux_reversal\", \"suddenly_essential\"]\n- grouped = self.solutions.groupby(['biomass', 'production'],\n- as_index=False, sort=False)\n- return grouped.get_group(item)[columns]\n+ return self.groups.get_group(item).copy()\ndef nth_panel(self, index):\n\"\"\"\n@@ -615,9 +615,7 @@ class DifferentialFVAResult(StrainDesignMethodResult):\nWhen the solutions were still based on pandas.Panel this was simply\nself.solutions.iloc\n\"\"\"\n- grouped = self.solutions.groupby(['biomass', 'production'],\n- as_index=False, sort=False)\n- return grouped.get_group(sorted(grouped.groups.keys())[index]).copy()\n+ return self.groups.get_group(sorted(self.groups.groups.keys())[index]).copy()\ndef plot(self, index=None, variables=None, grid=None, width=None, height=None, title=None, palette=None, **kwargs):\nif index is not None:\n@@ -668,8 +666,7 @@ class DifferentialFVAResult(StrainDesignMethodResult):\ndf.sort_values('normalized_gaps', inplace=True)\ndisplay(df)\n- num = len(self.solutions.groupby(['biomass', 'production'],\n- as_index=False, sort=False))\n+ num = len(self.groups)\ninteract(_data_frame, solution=(1, num))\nreturn ''\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: upgrade groupby |
89,734 | 27.06.2019 12:30:51 | -7,200 | 9fe4646ac6cf8305c1d4d80302a8dfae4eff8aa7 | fix: change target generation | [
{
"change_type": "MODIFY",
"old_path": "cameo/core/target.py",
"new_path": "cameo/core/target.py",
"diff": "@@ -96,13 +96,26 @@ class FluxModulationTarget(Target):\n\"\"\"\n__gnomic_feature_type__ = 'flux'\n- def __init__(self, id, value, reference_value, *args, **kwargs):\n- super(FluxModulationTarget, self).__init__(id, *args, **kwargs)\n+ def __init__(self, id, value, reference_value, fold_change=None, **kwargs):\n+ super(FluxModulationTarget, self).__init__(id, **kwargs)\n# TODO: refactor targets to make the following work\n# if value == 0:\n# raise ValueError(\"Please use ReactionKnockoutTarget if flux = 0.\")\nself._value = value\nself._reference_value = reference_value\n+ if fold_change is not None:\n+ self.fold_change = fold_change\n+ else:\n+ try:\n+ # FIXME (Moritz): Using absolute values here doesn't make sense\n+ # to me.\n+ ref = abs(self._reference_value)\n+ val = abs(self._value)\n+ self.fold_change = (val - ref) / ref\n+ except TypeError:\n+ self.fold_change = numpy.nan\n+ except ZeroDivisionError:\n+ self.fold_change = numpy.inf\ndef get_model_target(self, model):\nraise NotImplementedError\n@@ -133,22 +146,6 @@ class FluxModulationTarget(Target):\nelse:\nreturn False\n- @property\n- def fold_change(self):\n- \"\"\"\n- (B - A)/A\n-\n- Return\n- ------\n- float\n- \"\"\"\n- try:\n- ref = abs(self._reference_value)\n- val = abs(self._value)\n- return (val - ref) / ref\n- except ZeroDivisionError:\n- return numpy.inf\n-\ndef __str__(self):\nreturn genotype_to_string(Genotype([self.to_gnomic()]))\n@@ -160,7 +157,7 @@ class FluxModulationTarget(Target):\nelif self.fold_change < 0:\nreturn \"<FluxModulationTarget DOWN(%.3f)-%s>\" % (self.fold_change, self.id)\nelse:\n- raise RuntimeError(\"fold_change shouldn't be 0\")\n+ raise ValueError(\"fold_change shouldn't be 0\")\ndef __hash__(self):\nreturn hash(str(self))\n@@ -398,8 +395,10 @@ class GeneKnockoutTarget(GeneModulationTarget):\nclass ReactionModulationTarget(FluxModulationTarget):\n__gnomic_feature_type__ = \"reaction\"\n- def __init__(self, id, value, reference_value):\n- super(ReactionModulationTarget, self).__init__(id, value, reference_value)\n+ def __init__(self, id, value, reference_value, **kwargs):\n+ super(ReactionModulationTarget, self).__init__(\n+ id, value, reference_value, **kwargs\n+ )\ndef get_model_target(self, model):\nreturn model.reactions.get_by_id(self.id)\n"
},
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -469,58 +469,21 @@ class DifferentialFVA(StrainDesignMethod):\ntotal = pandas.concat(collection, ignore_index=True, copy=False)\ntotal.sort_values(['biomass', 'production', 'reaction'], inplace=True)\ntotal.index = total['reaction']\n- return DifferentialFVAResult(total, self.envelope, self.reference_flux_ranges, self.reference_flux_dist)\n+ return DifferentialFVAResult(total, self.envelope, self.reference_flux_ranges)\nclass DifferentialFVAResult(StrainDesignMethodResult):\n- def __init__(self, solutions, phase_plane, reference_fva, reference_fluxes, *args, **kwargs):\n+ def __init__(self, solutions, phase_plane, reference_fva, **kwargs):\nself.phase_plane = phase_plane\n- super(DifferentialFVAResult, self).__init__(self._generate_designs(solutions, reference_fva, reference_fluxes),\n- *args, **kwargs)\n+ super(DifferentialFVAResult, self).__init__(self._generate_designs(solutions, reference_fva), **kwargs)\nself.reference_fva = reference_fva\n- self.reference_fluxes = reference_fluxes\nself.solutions = solutions\nself.groups = self.solutions.groupby(\n('biomass', 'production'), as_index=False, sort=False\n)\n@classmethod\n- def _closest_bound(cls, ref_interval, row_interval):\n- \"\"\"\n- Finds the closest bound (upper or lower) of the reference to the interval.\n- It returns the name of the bound and the sign.\n-\n- Parameters\n- ----------\n- ref_interval: tuple, list\n- The reference interval.\n- row_interval: tuple, list\n- The row interval\n-\n- Returns\n- -------\n- string, bool\n-\n- \"\"\"\n-\n- distances = [ref_interval[0] - row_interval[1], ref_interval[1] - row_interval[0]]\n- # if the dist(ref_lb, ref_ub) > dist(ref_ub, row_lb)\n- if distances[0] > distances[1]:\n- # if ref_lb > 0\n- if row_interval[0] > 0:\n- return 'lower_bound', True\n- else:\n- return 'upper_bound', False\n- # if the dist(ref_lb, ref_ub) < dist(ref_ub, row_lb)\n- else:\n- # if ref_lb > 0\n- if row_interval[0] > 0:\n- return 'upper_bound', True\n- else:\n- return 'lower_bound', False\n-\n- @classmethod\n- def _generate_designs(cls, solutions, reference_fva, reference_fluxes):\n+ def _generate_designs(cls, solutions, reference_fva):\n\"\"\"\nGenerates strain designs for Differential FVA.\n@@ -531,8 +494,9 @@ class DifferentialFVAResult(StrainDesignMethodResult):\n#### 2. Flux reversal\n- If the new flux is negative then it should be at least the upper bound of the interval.\n- Otherwise it should be at least the lower bound of the interval.\n+ If the new flux is negative then it should be at least the upper\n+ bound of the interval. Otherwise it should be at least the lower\n+ bound of the interval.\n#### 3. The flux increases or decreases\n@@ -557,8 +521,6 @@ class DifferentialFVAResult(StrainDesignMethodResult):\nThe DifferentialFVA panel with all the solutions. Each DataFrame is a design.\nreference_fva: pandas.DataFrame\nThe FVA limits for the reference strain.\n- reference_fluxes:\n- The optimal flux distribution for the reference strain.\nReturns\n-------\n@@ -568,39 +530,78 @@ class DifferentialFVAResult(StrainDesignMethodResult):\ndesigns = []\nfor _, solution in solutions.groupby(('biomass', 'production'), as_index=False, sort=False):\ntargets = []\n- relevant_targets = solution.loc[\n- (numpy.abs(solution['normalized_gaps']) > non_zero_flux_threshold) & (\n- numpy.logical_not(solution['excluded'])) & (\n- numpy.logical_not(solution['free_flux']))\n+ relevant_targets = solution[\n+ (solution['normalized_gaps'].abs() > non_zero_flux_threshold) & (\n+ ~solution['excluded']) & (\n+ ~solution['free_flux'])\n]\n- for rid, relevant_row in relevant_targets.iterrows():\n- if relevant_row.KO:\n+ # Generate all knock-out targets.\n+ for rid in relevant_targets.loc[relevant_targets[\"KO\"], \"reaction\"]:\ntargets.append(ReactionKnockoutTarget(rid))\n- elif relevant_row.flux_reversal:\n- if reference_fva['upper_bound'][rid] > 0:\n- targets.append(ReactionInversionTarget(rid,\n- value=float_ceil(relevant_row.upper_bound, ndecimals),\n- reference_value=reference_fluxes[rid]))\n+ # Generate all flux inversion targets.\n+ for row in relevant_targets[\n+ relevant_targets[\"flux_reversal\"]\n+ ].itertuples():\n+ rid = row.Index\n+ ref_lower = reference_fva.at[rid, 'lower_bound']\n+ ref_upper = reference_fva.at[rid, 'upper_bound']\n+ if ref_upper > 0:\n+ # Production point is negative so closest inversion is\n+ # from reference lower bound to production upper bound.\n+ targets.append(ReactionInversionTarget(\n+ rid,\n+ value=row.upper_bound,\n+ reference_value=ref_lower\n+ ))\nelse:\n- targets.append(ReactionInversionTarget(rid,\n- value=float_floor(relevant_row.lower_bound, ndecimals),\n- reference_value=reference_fluxes[rid]))\n+ # Production point is positive so closest inversion is\n+ # from reference upper bound to production lower bound.\n+ targets.append(ReactionInversionTarget(\n+ rid,\n+ value=row.lower_bound,\n+ reference_value=ref_upper\n+ ))\n+ # Generate all suddenly essential targets where we know the\n+ # reference interval lies around zero.\n+ for row in relevant_targets[\n+ relevant_targets[\"suddenly_essential\"]\n+ ].itertuples():\n+ rid = row.Index\n+ if row.lower_bound > 0:\n+ targets.append(ReactionModulationTarget(\n+ rid,\n+ value=row.lower_bound,\n+ reference_value=reference_fva.at[rid, \"upper_bound\"]\n+ ))\nelse:\n- gap_sign = relevant_row.normalized_gaps > 0\n-\n- ref_interval = reference_fva[['lower_bound', 'upper_bound']].loc[rid].values\n- row_interval = (relevant_row.lower_bound, relevant_row.upper_bound)\n-\n- closest_bound, ref_sign = cls._closest_bound(ref_interval, row_interval)\n-\n- if gap_sign ^ ref_sign:\n- value = float_ceil(relevant_row.upper_bound, ndecimals)\n+ targets.append(ReactionModulationTarget(\n+ rid,\n+ value=row.upper_bound,\n+ reference_value=reference_fva.at[rid, \"lower_bound\"]\n+ ))\n+ # Generate all other flux modulation targets.\n+ for row in relevant_targets[\n+ (~relevant_targets[\"KO\"]) & (\n+ ~relevant_targets[\"flux_reversal\"]) & (\n+ ~relevant_targets[\"suddenly_essential\"])\n+ ].itertuples():\n+ rid = row.Index\n+ ref_lower = reference_fva.at[rid, 'lower_bound']\n+ ref_upper = reference_fva.at[rid, 'upper_bound']\n+ if row.normalized_gaps > 0:\n+ targets.append(ReactionModulationTarget(\n+ rid,\n+ value=row.lower_bound,\n+ reference_value=ref_upper,\n+ fold_change=row.normalized_gaps\n+ ))\nelse:\n- value = float_floor(relevant_row.lower_bound, ndecimals)\n-\n- targets.append(ReactionModulationTarget(rid,\n- value=value,\n- reference_value=reference_fva[closest_bound][rid]))\n+ targets.append(ReactionModulationTarget(\n+ rid,\n+ value=row.upper_bound,\n+ reference_value=ref_lower,\n+ fold_change=row.normalized_gaps\n+ ))\ndesigns.append(StrainDesign(targets))\nreturn designs\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: change target generation |
89,734 | 03.07.2019 12:30:30 | -7,200 | 24c05f17617b539a86b4bc0d467f6e2f3299e92c | fix: ignore conflicting targets | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -589,6 +589,12 @@ class DifferentialFVAResult(StrainDesignMethodResult):\nref_lower = reference_fva.at[rid, 'lower_bound']\nref_upper = reference_fva.at[rid, 'upper_bound']\nif row.normalized_gaps > 0:\n+ # For now we ignore reactions that have a positive\n+ # normalized gap, indicating that their flux is important\n+ # for production, but where the reference flux is higher\n+ # than the production flux.\n+ if abs(ref_upper) > abs(row.lower_bound):\n+ continue\ntargets.append(ReactionModulationTarget(\nrid,\nvalue=row.lower_bound,\n@@ -596,6 +602,12 @@ class DifferentialFVAResult(StrainDesignMethodResult):\nfold_change=row.normalized_gaps\n))\nelse:\n+ # For now we ignore reactions that have a negative\n+ # normalized gap, indicating that their flux needs to\n+ # decrease in production, but where the production\n+ # interval is larger than the reference interval.\n+ if abs(row.upper_bound) > abs(ref_lower):\n+ continue\ntargets.append(ReactionModulationTarget(\nrid,\nvalue=row.upper_bound,\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: ignore conflicting targets |
89,738 | 02.11.2020 21:58:30 | -3,600 | 955c399b38025954c8e69ae900c851840febbe74 | chore: remove bokeh and ggplot from general plotting | [
{
"change_type": "DELETE",
"old_path": "cameo/visualization/plotting/with_bokeh.py",
"new_path": null,
"diff": "-# Copyright 2016 Novo Nordisk Foundation Center for Biosustainability, DTU.\n-#\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-#\n-# http://www.apache.org/licenses/LICENSE-2.0\n-#\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-from __future__ import absolute_import\n-\n-from bokeh.charts import Line, Bar\n-from bokeh.models import FactorRange\n-from bokeh.layouts import gridplot\n-from bokeh.plotting import figure, show\n-\n-from cameo.util import partition, inheritdocstring, in_ipnb\n-from cameo.visualization.plotting.abstract import AbstractPlotter\n-\n-\n-class BokehPlotter(AbstractPlotter, metaclass=inheritdocstring):\n- def __init__(self, **options):\n- if in_ipnb():\n- from bokeh.io import output_notebook\n- output_notebook(hide_banner=True)\n- super(BokehPlotter, self).__init__(**options)\n-\n- def _add_fva_bars(self, plot, factors, dataframe, height, step, color, strain):\n- alpha = self.get_option('alpha')\n-\n- left = dataframe.ub.tolist()\n- right = dataframe.lb.tolist()\n- bottom = [(i + 1.5) + height for i in range(len(factors))]\n- top = [(i + 1.5) + height + step for i in range(len(factors))]\n-\n- plot.quad(top=top, bottom=bottom, left=left, right=right, color=color, legend=strain, fill_alpha=alpha)\n-\n- def flux_variability_analysis(self, dataframe, grid=None, width=None, height=None, title=None,\n- palette=None, x_axis_label=None, y_axis_label=None):\n- palette = self.get_option('palette') if palette is None else palette\n- width = self.get_option('width') if width is None else width\n- strains = dataframe[\"strain\"].unique()\n- factors = dataframe['reaction'].unique().tolist()\n- x_range = [min(dataframe.lb) - 5, max(dataframe.ub) + 5]\n-\n- width, height = self.golden_ratio(width, height)\n-\n- plot = figure(title=title, plot_width=width, plot_height=height,\n- x_range=x_range, y_range=FactorRange(factors=[\"\"] + factors + [\"\"]),\n- min_border=5)\n-\n- plot.line([0, 0], [0, len(factors) + 3], line_color=\"black\", line_width=1.5, line_alpha=1)\n-\n- n = len(strains)\n- step = 1.0 / float(len(strains))\n- for strain, i, color in zip(strains, range(n), self._palette(palette, n)):\n- _dataframe = dataframe[dataframe[\"strain\"] == strain]\n- self._add_fva_bars(plot, factors, _dataframe, i * step, step, color, strain)\n-\n- if x_axis_label:\n- plot.xaxis.axis_label = x_axis_label\n- if y_axis_label:\n- plot.yaxis.axis_label = y_axis_label\n-\n- return plot\n-\n- def _add_production_envelope(self, plot, dataframe, strain, color=None):\n- patch_alpha = self.get_option('alpha')\n- ub = dataframe[\"ub\"].values.tolist()\n- lb = dataframe[\"lb\"].values.tolist()\n- var = dataframe[\"value\"].values\n-\n- x = [v for v in var] + [v for v in reversed(var)]\n- y = [v for v in lb] + [v for v in reversed(ub)]\n-\n- plot.patch(x=x, y=y, fill_color=color, fill_alpha=patch_alpha, legend=strain)\n-\n- if \"label\" in dataframe.columns:\n- plot.text(dataframe[\"label\"].values, var, ub)\n-\n- plot.line(var, ub, color=color)\n- plot.line(var, lb, color=color)\n- if ub[-1] != lb[-1]:\n- plot.line((var[-1], var[-1]), (ub[-1], lb[-1]), color=color)\n-\n- def production_envelope(self, dataframe, grid=None, width=None, height=None, title=None, points=None,\n- points_colors=None, palette='RdYlBu', x_axis_label=None, y_axis_label=None):\n- strains = dataframe[\"strain\"].unique()\n- palette = self.get_option('palette') if palette is None else palette\n- width = self.get_option('width') if width is None else width\n- if not height:\n- width, height = self.golden_ratio(width, height)\n-\n- plot = figure(title=title, plot_width=width, plot_height=height)\n- for strain, color in zip(strains, self._palette(palette, len(strains))):\n- _dataframe = dataframe[dataframe[\"strain\"] == strain]\n- self._add_production_envelope(plot, _dataframe, strain, color=color)\n-\n- if points is not None:\n- plot.scatter(*zip(*points), color=\"green\" if points_colors is None else points_colors)\n-\n- if x_axis_label:\n- plot.xaxis.axis_label = x_axis_label\n- if y_axis_label:\n- plot.yaxis.axis_label = y_axis_label\n-\n- if grid is not None:\n- grid.append(plot)\n- return grid\n-\n- return plot\n-\n- def line(self, dataframe, width=None, height=None, palette=None, title=\"Line\",\n- x_axis_label=None, y_axis_label=None, grid=None):\n-\n- palette = self.get_option('palette') if palette is None else palette\n- width = self.get_option('width') if width is None else width\n-\n- if not height:\n- width, height = self.golden_ratio(width, height)\n-\n- palette = self._palette(palette, len(dataframe.index))\n-\n- line = Line(dataframe.T, legend=\"top_right\", color=palette, ylabel=y_axis_label, xlabel=y_axis_label,\n- title=title, width=width, height=height)\n-\n- if grid is not None:\n- grid.append(line)\n- return grid\n-\n- return line\n-\n- def frequency(self, dataframe, width=None, height=None, palette=None, title=\"Frequency plot\",\n- x_axis_label=None, y_axis_label=\"Frequency\", grid=None):\n- palette = self.get_option('palette') if palette is None else palette\n- width = self.get_option('width') if width is None else width\n-\n- if not height:\n- width, height = self.golden_ratio(width, height)\n-\n- palette = self._palette(palette, len(dataframe.index))\n-\n- bar = Bar(dataframe, color=palette, values='frequency', ylabel=y_axis_label, xlabel=x_axis_label,\n- title=title, width=width, height=height)\n-\n- if grid is not None:\n- grid.append(bar)\n- return grid\n-\n- return bar\n-\n-\n- @property\n- def _display(self):\n- return show\n-\n- @staticmethod\n- def _make_grid(grid):\n- return gridplot(children=partition(grid.plots, grid.n_rows),\n- name=grid.title)\n"
},
{
"change_type": "DELETE",
"old_path": "cameo/visualization/plotting/with_ggplot.py",
"new_path": null,
"diff": "-# Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU.\n-\n-# Licensed under the Apache License, Version 2.0 (the \"License\");\n-# you may not use this file except in compliance with the License.\n-# You may obtain a copy of the License at\n-\n-# http://www.apache.org/licenses/LICENSE-2.0\n-\n-# Unless required by applicable law or agreed to in writing, software\n-# distributed under the License is distributed on an \"AS IS\" BASIS,\n-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n-# See the License for the specific language governing permissions and\n-# limitations under the License.\n-from __future__ import absolute_import\n-\n-from math import ceil\n-\n-from warnings import warn\n-from ggplot import scale_colour_manual, geom_area, geom_tile, scale_x_continuous, scale_y_continuous, aes, facet_grid\n-\n-from cameo.util import in_ipnb, inheritdocstring\n-from cameo.visualization.plotting import AbstractPlotter\n-\n-\n-class GGPlotPlotter(AbstractPlotter, metaclass=inheritdocstring):\n- def __init__(self, **options):\n- warn(\"ggplot interface is under construction...\")\n-\n- super(GGPlotPlotter, self).__init__(**options)\n-\n- def production_envelope(self, dataframe, grid=None, width=None, height=None, title=None, points=None,\n- points_colors=None, palette=None, x_axis_label=None, y_axis_label=None):\n-\n- palette = self.get_option('palette') if palette is None else palette\n- width = self.get_option('width') if width is None else width\n- colors = self._palette(palette, len(dataframe.strain.unique()))\n-\n- plot = aes(data=dataframe, ymin=\"lb\", ymax=\"ub\", x=\"value\", color=scale_colour_manual(colors)) + geom_area()\n- if title:\n- plot += geom_tile(title)\n- if x_axis_label:\n- plot += scale_x_continuous(name=x_axis_label)\n- if y_axis_label:\n- plot += scale_y_continuous(name=y_axis_label)\n-\n- return plot\n-\n- def flux_variability_analysis(self, dataframe, grid=None, width=None, height=None, title=None, palette=None,\n- x_axis_label=None, y_axis_label=None):\n-\n- return aes(data=dataframe, )\n-\n- @property\n- def _display(self):\n- if in_ipnb():\n- from IPython.display import display\n- return display\n-\n- @staticmethod\n- def _make_grid(grid):\n- columns = ceil(grid.n_rows / len(grid.plots()))\n- return grid.plot[0] + facet_grid(grid.n_rows, columns, scales=\"fixed\")\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | chore: remove bokeh and ggplot from general plotting |
89,738 | 02.11.2020 21:59:02 | -3,600 | 37509402ec160a2b4a48c7ad33414cd8e5f962ed | refactor: remove automagic plot imports | [
{
"change_type": "MODIFY",
"old_path": "cameo/core/strain_design.py",
"new_path": "cameo/core/strain_design.py",
"diff": "@@ -23,7 +23,6 @@ from pandas import DataFrame\nfrom cameo.core.result import Result\nfrom cameo.core.target import EnsembleTarget, Target\n-from cameo.visualization.plotting import plotter\nfrom gnomic import Genotype\n@@ -180,7 +179,7 @@ class StrainDesignMethodResult(Result):\ndef _repr_html_(self):\nreturn self.data_frame._repr_html_()\n- def plot(self, grid=None, width=None, height=None, title=None, *args, **kwargs):\n+ def plot(self, plotter, grid=None, width=None, height=None, title=None, *args, **kwargs):\nif title is None:\ntitle = \"Target frequency plot for %s result\" % self.__method_name__\n"
},
{
"change_type": "MODIFY",
"old_path": "cameo/flux_analysis/analysis.py",
"new_path": "cameo/flux_analysis/analysis.py",
"diff": "@@ -29,10 +29,9 @@ from cobra.core import get_solution\nfrom cobra.util import fix_objective_as_constraint, get_context\nfrom cobra.exceptions import OptimizationError\nfrom numpy import trapz\n-from sympy import S\nfrom optlang.interface import UNBOUNDED, OPTIMAL\n+from optlang.symbolics import Zero\n-import cameo\nfrom cameo import config\nfrom cameo.core.result import Result\nfrom cameo.flux_analysis.util import remove_infeasible_cycles, fix_pfba_as_constraint\n@@ -40,7 +39,6 @@ from cameo.parallel import SequentialView\nfrom cameo.ui import notice\nfrom cameo.util import partition, _BIOMASS_RE_\nfrom cameo.core.utils import get_reaction_for\n-from cameo.visualization.plotting import plotter\nlogger = logging.getLogger(__name__)\n@@ -357,7 +355,7 @@ def _flux_variability_analysis(model, reactions=None):\nfva_sol = OrderedDict()\nlb_flags = dict()\nwith model:\n- model.objective = S.Zero\n+ model.objective = Zero\nmodel.objective.direction = 'min'\nfor reaction in reactions:\n@@ -760,7 +758,7 @@ class PhenotypicPhasePlaneResult(Result):\ndef data_frame(self):\nreturn pandas.DataFrame(self._phase_plane)\n- def plot(self, grid=None, width=None, height=None, title=None, axis_font_size=None, palette=None,\n+ def plot(self, plotter, grid=None, width=None, height=None, title=None, axis_font_size=None, palette=None,\npoints=None, points_colors=None, estimate='flux', **kwargs):\n\"\"\"plot phenotypic phase plane result\n@@ -882,7 +880,7 @@ class FluxVariabilityResult(Result):\ndef data_frame(self):\nreturn self._data_frame\n- def plot(self, index=None, grid=None, width=None, height=None, title=None, palette=None, **kwargs):\n+ def plot(self, plotter, index=None, grid=None, width=None, height=None, title=None, palette=None, **kwargs):\nif index is None:\nindex = self.data_frame.index[0:10]\nfva_result = self.data_frame.loc[index]\n"
},
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"new_path": "cameo/strain_design/deterministic/flux_variability_based.py",
"diff": "@@ -37,7 +37,6 @@ from pandas import DataFrame, pandas\nfrom cobra import Reaction, Metabolite\nfrom cobra.util import fix_objective_as_constraint\n-from cameo.visualization.plotting import plotter\nfrom cameo import config\nfrom cameo.ui import notice\n@@ -633,7 +632,7 @@ class DifferentialFVAResult(StrainDesignMethodResult):\nelse:\nself._plot_production_envelope(title=title, grid=grid, width=width, height=height)\n- def _plot_flux_variability_analysis(self, index, variables=None, title=None,\n+ def _plot_flux_variability_analysis(self, plotter, index, variables=None, title=None,\nwidth=None, height=None, palette=None, grid=None):\nif variables is None:\nvariables = self.reference_fva.index[0:10]\n@@ -1008,7 +1007,7 @@ class FSEOFResult(StrainDesignMethodResult):\n__method_name__ = \"FSEOF\"\n- def plot(self, grid=None, width=None, height=None, title=None, *args, **kwargs):\n+ def plot(self, plotter, grid=None, width=None, height=None, title=None, *args, **kwargs):\nif title is None:\ntitle = \"FSEOF fluxes\"\n"
},
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/linear_programming.py",
"new_path": "cameo/strain_design/deterministic/linear_programming.py",
"diff": "@@ -41,7 +41,6 @@ from cameo.flux_analysis.analysis import phenotypic_phase_plane, flux_variabilit\nfrom cameo.flux_analysis.simulation import fba\nfrom cameo.flux_analysis.structural import find_coupled_reactions_nullspace\nfrom cameo.util import reduce_reaction_set, decompose_reaction_groups\n-from cameo.visualization.plotting import plotter\nlogger = logging.getLogger(__name__)\n@@ -385,7 +384,7 @@ class OptKnockResult(StrainDesignMethodResult):\nfluxes = fba(self._model)\nfluxes.display_on_map(map_name=map_name, palette=palette)\n- def plot(self, index=0, grid=None, width=None, height=None, title=None, palette=None, **kwargs):\n+ def plot(self, plotter, index=0, grid=None, width=None, height=None, title=None, palette=None, **kwargs):\nwt_production = phenotypic_phase_plane(self._model, objective=self._target, variables=[self._biomass.id])\nwith self._model:\nfor ko in self.data_frame.loc[index, \"reactions\"]:\n"
},
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/heuristic/evolutionary_based.py",
"new_path": "cameo/strain_design/heuristic/evolutionary_based.py",
"diff": "@@ -38,7 +38,6 @@ from cameo.strain_design.heuristic.evolutionary.optimization import GeneKnockout\nfrom cameo.strain_design.heuristic.evolutionary.processing import process_reaction_knockout_solution, \\\nprocess_gene_knockout_solution, process_reaction_swap_solution\nfrom cameo.util import TimeMachine\n-from cameo.visualization.plotting import plotter\nfrom cameo.core.utils import get_reaction_for\n__all__ = [\"OptGene\"]\n@@ -294,7 +293,7 @@ class OptGeneResult(StrainDesignMethodResult):\nfluxes = self._simulation_method(self._model, **self._simulation_kwargs)\nfluxes.display_on_map(map_name=map_name, palette=palette)\n- def plot(self, index=0, grid=None, width=None, height=None, title=None, palette=None, **kwargs):\n+ def plot(self, plotter, index=0, grid=None, width=None, height=None, title=None, palette=None, **kwargs):\nwt_production = phenotypic_phase_plane(self._model, objective=self._target, variables=[self._biomass])\nwith self._model:\nfor ko in self.data_frame.loc[index, \"reactions\"]:\n@@ -483,7 +482,7 @@ class HeuristicOptSwapResult(StrainDesignMethodResult):\nfluxes = self._simulation_method(self._model, **self._simulation_kwargs)\nfluxes.display_on_map(map_name=map_name, palette=palette)\n- def plot(self, index=0, grid=None, width=None, height=None, title=None, palette=None, **kwargs):\n+ def plot(self, plotter, index=0, grid=None, width=None, height=None, title=None, palette=None, **kwargs):\nwt_production = phenotypic_phase_plane(self._model, objective=self._target, variables=[self._biomass])\nwith self._model:\nfor ko in self.data_frame.loc[index, \"reactions\"]:\n"
},
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/pathway_prediction/pathway_predictor.py",
"new_path": "cameo/strain_design/pathway_prediction/pathway_predictor.py",
"diff": "@@ -39,7 +39,6 @@ from cameo.core.target import ReactionKnockinTarget\nfrom cameo.data import metanetx\nfrom cameo.strain_design.pathway_prediction import util\nfrom cameo.util import TimeMachine\n-from cameo.visualization.plotting import plotter\n__all__ = ['PathwayPredictor']\n@@ -172,7 +171,9 @@ class PathwayPredictions(StrainDesignMethodResult):\n# TODO: small pathway visualizations would be great.\nraise NotImplementedError\n- def plot_production_envelopes(self, model, objective=None, title=None):\n+ def plot_production_envelopes(\n+ self, plotter, model, objective=None, title=None\n+ ):\nrows = int(ceil(len(self.pathways) / 2.0))\ntitle = \"Production envelops for %s\" % self.pathways[0].product.name if title is None else title\ngrid = plotter.grid(n_rows=rows, title=title)\n"
},
{
"change_type": "MODIFY",
"old_path": "cameo/visualization/plotting/__init__.py",
"new_path": "cameo/visualization/plotting/__init__.py",
"diff": "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n-from __future__ import absolute_import\n-\n-from warnings import warn\n-\n-from cameo.visualization.plotting.abstract import AbstractPlotter\n-\n-__all__ = [\"plotter\"]\n-\n-_engine = None\n-_engines = {}\n-\n-try:\n- from cameo.visualization.plotting.with_bokeh import BokehPlotter\n-\n- _engine = BokehPlotter() if _engine is None else _engine\n- _engines[\"bokeh\"] = BokehPlotter\n-except ImportError:\n- pass\n-\n-try:\n- from cameo.visualization.plotting.with_plotly import PlotlyPlotter\n-\n- _engine = PlotlyPlotter(mode='offline') if _engine is None else _engine\n- _engines[\"plotly\"] = PlotlyPlotter\n-except ImportError:\n- pass\n-\n-try:\n- from cameo.visualization.plotting.with_plotly import GGPlotPlotter\n-\n- _engine = GGPlotPlotter() if _engine is None else _engine\n- _engines[\"ggplot\"] = GGPlotPlotter\n-except ImportError:\n- pass\n-\n-if _engine is None:\n- warn(\"Cannot import any plotting library. Please install one of 'plotly', 'bokeh' or 'ggplot' if you want to\"\n- \" use any plotting function.\")\n- _engine = AbstractPlotter()\n-\n-\n-class _plotting:\n- def __init__(self, engine):\n- self.__dict__['_engine'] = engine\n-\n- def __getattr__(self, item):\n- if item not in [\"_engine\", \"engine\"]:\n- return getattr(self.__dict__['_engine'], item)\n- else:\n- return self.__dict__['_engine']\n-\n- def __setattr__(self, key, item):\n- if key not in [\"_engine\", \"engine\"]:\n- raise KeyError(key)\n- else:\n- if isinstance(item, str):\n- item = _engines[item]()\n-\n- if not isinstance(item, AbstractPlotter):\n- raise AssertionError(\"Invalid engine %s\" % item)\n-\n- self.__dict__['_engine'] = item\n-\n-\n-plotter = _plotting(_engine)\n"
},
{
"change_type": "MODIFY",
"old_path": "cameo/visualization/plotting/with_plotly.py",
"new_path": "cameo/visualization/plotting/with_plotly.py",
"diff": "@@ -16,7 +16,7 @@ from __future__ import absolute_import\nimport math\n-import plotly.graph_objs as go\n+import plotly.graph_objects as go\nfrom plotly import tools\nfrom cameo.util import zip_repeat, in_ipnb, inheritdocstring, partition\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | refactor: remove automagic plot imports |
89,738 | 02.11.2020 22:00:02 | -3,600 | c1fca15506da700a0e7d902267fc3409b9fd6b45 | chore: upgrade plotly dependency | [
{
"change_type": "MODIFY",
"old_path": "setup.py",
"new_path": "setup.py",
"diff": "@@ -45,7 +45,7 @@ requirements = ['numpy>=1.9.1',\nextra_requirements = {\n'docs': ['Sphinx>=1.3.5', 'numpydoc>=0.5'],\n- 'plotly': ['plotly>=3.0.0'],\n+ 'plotly': ['plotly>=4.12.0'],\n'bokeh': ['bokeh<=0.12.1'],\n'jupyter': ['jupyter>=1.0.0', 'ipywidgets>=4.1.1'],\n'test': ['pytest', 'pytest-cov', 'pytest-benchmark'],\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | chore: upgrade plotly dependency |
89,738 | 02.11.2020 22:01:00 | -3,600 | 30c215f3f19daa22755a587faca95f548d3e2aba | test: check that production envelop is not broken | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "tests/test_visualization.py",
"diff": "+# Copyright 2019 Novo Nordisk Foundation Center for Biosustainability, DTU.\n+#\n+# Licensed under the Apache License, Version 2.0 (the \"License\");\n+# you may not use this file except in compliance with the License.\n+# You may obtain a copy of the License at\n+#\n+# http://www.apache.org/licenses/LICENSE-2.0\n+#\n+# Unless required by applicable law or agreed to in writing, software\n+# distributed under the License is distributed on an \"AS IS\" BASIS,\n+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n+# See the License for the specific language governing permissions and\n+# limitations under the License.\n+\n+from cameo.flux_analysis.analysis import phenotypic_phase_plane\n+from cameo.visualization.plotting.with_plotly import PlotlyPlotter\n+\n+plotter = PlotlyPlotter()\n+\n+\n+def test_ppp_plotly(model):\n+ \"\"\"Test if at least it doesn't raise an exception.\"\"\"\n+ production_envelope = phenotypic_phase_plane(\n+ model,\n+ variables=[model.reactions.Biomass_Ecoli_core_N_lp_w_fsh_GAM_rp__Nmet2],\n+ objective=model.metabolites.succ_e,\n+ )\n+ # pass a grid argument so that it doesn't open a browser tab\n+ production_envelope.plot(plotter, height=400, grid=[])\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | test: check that production envelop is not broken |
89,738 | 05.11.2020 16:23:30 | -3,600 | 26355fe2e849065fae8267fb629107095bd3ae20 | test: add plotly before build on CI | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -47,7 +47,7 @@ after_success:\nbefore_deploy:\n- if [[ $TRAVIS_PYTHON_VERSION == \"3.6\" ]]; then\n- pip install .[docs,jupyter];\n+ pip install .[docs,jupyter,plotly];\ncd docs && make apidoc && make html && touch _build/html/.nojekyll;\nfi\n- cd \"${TRAVIS_BUILD_DIR}\"\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | test: add plotly before build on CI |
89,738 | 05.11.2020 18:41:27 | -3,600 | 37c25259b01ecc7fb97e72d7f66363940d39e718 | test: instal plotly on tox | [
{
"change_type": "MODIFY",
"old_path": ".travis.yml",
"new_path": ".travis.yml",
"diff": "@@ -47,7 +47,7 @@ after_success:\nbefore_deploy:\n- if [[ $TRAVIS_PYTHON_VERSION == \"3.6\" ]]; then\n- pip install .[docs,jupyter,plotly];\n+ pip install .[docs,jupyter];\ncd docs && make apidoc && make html && touch _build/html/.nojekyll;\nfi\n- cd \"${TRAVIS_BUILD_DIR}\"\n"
},
{
"change_type": "MODIFY",
"old_path": "tox.ini",
"new_path": "tox.ini",
"diff": "@@ -6,6 +6,7 @@ deps =\npytest\npytest-cov\npytest-benchmark\n+ plotly\nwhitelist_externals =\nobabel\nsetenv =\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | test: instal plotly on tox |
89,738 | 06.11.2020 10:51:35 | -3,600 | dace3897944752eb2efe6726c0fb2d9b9a00c86e | fix: use S instead of deprecated singleton | [
{
"change_type": "MODIFY",
"old_path": "cameo/flux_analysis/simulation.py",
"new_path": "cameo/flux_analysis/simulation.py",
"diff": "@@ -48,8 +48,8 @@ logger = logging.getLogger(__name__)\nadd = Add._from_args\nmul = Mul._from_args\n-NegativeOne = sympy.singleton.S.NegativeOne\n-One = sympy.singleton.S.One\n+NegativeOne = sympy.S.NegativeOne\n+One = sympy.S.One\nFloatOne = sympy.Float(1)\nRealNumber = sympy.RealNumber\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: use S instead of deprecated singleton |
89,740 | 09.11.2020 13:10:17 | -3,600 | e2fdbf86c56798a02b9df1323fc25ad3d38b0892 | Update analysis.py
* Update analysis.py
Incorrect return type documented which is confusing for usage.
* Fix flaxe8 line length | [
{
"change_type": "MODIFY",
"old_path": "cameo/flux_analysis/analysis.py",
"new_path": "cameo/flux_analysis/analysis.py",
"diff": "@@ -201,8 +201,9 @@ def flux_variability_analysis(model, reactions=None, fraction_of_optimum=0., pfb\nReturns\n-------\n- pandas.DataFrame\n- Pandas DataFrame containing the results of the flux variability analysis.\n+ FluxVariabilityResult\n+ FluxVariabilityResult with DataFrame data_frame property containing the results of the flux variability\n+ analysis.\n\"\"\"\nif view is None:\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | Update analysis.py (#259)
* Update analysis.py
Incorrect return type documented which is confusing for usage.
* Fix flaxe8 line length
Co-authored-by: Jorge Carrasco <[email protected]> |
89,738 | 04.06.2021 10:05:24 | -7,200 | 482e5bed6a36c90b8a47082b0b9ef808f4f4db77 | fix: reconcile blocked with excluded reactions in OptKnock | [
{
"change_type": "MODIFY",
"old_path": "cameo/strain_design/deterministic/linear_programming.py",
"new_path": "cameo/strain_design/deterministic/linear_programming.py",
"diff": "@@ -120,13 +120,16 @@ class OptKnock(StrainDesignMethod):\nif fraction_of_optimum is not None:\nfix_objective_as_constraint(self._model, fraction=fraction_of_optimum)\n- if remove_blocked:\n- self._remove_blocked_reactions()\n+ blocked = self._remove_blocked_reactions() if remove_blocked else []\nif exclude_reactions:\n# Convert exclude_reactions to reaction ID's\nexclude_reactions = [\n- r.id if isinstance(r, cobra.core.Reaction) else r for r in exclude_reactions\n+ r.id if isinstance(r, cobra.core.Reaction) else r\n+ for r in exclude_reactions\n]\n+ # if a blocked reaction were in exclude reactions, it would raise\n+ # because blocked reactions are removed from the model\n+ exclude_reactions = [r_id for r_id in exclude_reactions if r_id not in blocked]\nfor r_id in exclude_reactions:\nif r_id not in self._model.reactions:\nraise ValueError(\"Excluded reaction {} is not in the model\".format(r_id))\n@@ -139,13 +142,13 @@ class OptKnock(StrainDesignMethod):\ndef _remove_blocked_reactions(self):\nfva_res = flux_variability_analysis(self._model, fraction_of_optimum=0)\n- # FIXME: Iterate over the index only (reaction identifiers).\nblocked = [\n- self._model.reactions.get_by_id(reaction) for reaction, row in fva_res.data_frame.iterrows()\n+ reaction for reaction, row in fva_res.data_frame.iterrows()\nif (round(row[\"lower_bound\"], config.ndecimals) == round(\nrow[\"upper_bound\"], config.ndecimals) == 0)\n]\nself._model.remove_reactions(blocked)\n+ return blocked\ndef _reduce_to_nullspace(self, reactions):\nself.reaction_groups = find_coupled_reactions_nullspace(self._model)\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | fix: reconcile blocked with excluded reactions in OptKnock |
89,741 | 12.10.2021 14:16:35 | -7,200 | 50b27dae08eb65c26697260bb35df17a84ed8dca | Skip problematic pickling problems in test_run_single_objective | [
{
"change_type": "MODIFY",
"old_path": "tests/test_strain_design_heuristics.py",
"new_path": "tests/test_strain_design_heuristics.py",
"diff": "@@ -954,13 +954,15 @@ class TestReactionKnockoutOptimization:\nassert len(results.data_frame.targets) > 0\nassert len(results.data_frame.targets) == len(results.data_frame.targets.apply(tuple).unique())\n- with open(result_file, 'wb') as in_file:\n- pickle.dump(results, in_file)\n+ # with open(result_file, 'wb') as in_file:\n+ # print(results)\n+ # print(in_file)\n+ # pickle.dump(results, in_file)\n- with open(result_file, 'rb') as in_file:\n- expected_results = pickle.load(in_file)\n+ # with open(result_file, 'rb') as in_file:\n+ # expected_results = pickle.load(in_file)\n- assert results.seed == expected_results.seed\n+ # assert results.seed == expected_results.seed\ndef test_run_reaction_single_ko_objective_benchmark(self, benchmark, reaction_ko_single_objective):\nbenchmark(reaction_ko_single_objective.run, max_evaluations=3000, pop_size=10, view=SequentialView(), seed=SEED)\n@@ -1048,13 +1050,14 @@ class TestGeneKnockoutOptimization:\nassert len(results.data_frame.targets) == len(results.data_frame.targets.apply(tuple).unique())\n- with open(result_file, 'wb') as in_file:\n- pickle.dump(results, in_file)\n+ # with open(result_file, 'wb') as in_file:\n+ # print(results)\n+ # pickle.dump(results, in_file)\n- with open(result_file, 'rb') as in_file:\n- expected_results = pickle.load(in_file)\n+ # with open(result_file, 'rb') as in_file:\n+ # expected_results = pickle.load(in_file)\n- assert results.seed == expected_results.seed\n+ # assert results.seed == expected_results.seed\ndef test_run_gene_ko_single_objective_benchmark(self, gene_ko_single_objective, benchmark):\nbenchmark(gene_ko_single_objective.run, max_evaluations=3000, pop_size=10, view=SequentialView(), seed=SEED)\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | Skip problematic pickling problems in test_run_single_objective |
89,741 | 12.10.2021 15:29:31 | -7,200 | 85616899d16bfc760e06810178acb03c4d76119f | Skip more pickle problems | [
{
"change_type": "MODIFY",
"old_path": "tests/test_strain_design_heuristics.py",
"new_path": "tests/test_strain_design_heuristics.py",
"diff": "@@ -1001,13 +1001,13 @@ class TestReactionKnockoutOptimization:\nassert len(results.data_frame.targets) == len(results.data_frame.targets.apply(tuple).unique())\n- with open(result_file, 'wb') as in_file:\n- pickle.dump(results, in_file)\n+ # with open(result_file, 'wb') as in_file:\n+ # pickle.dump(results, in_file)\n- with open(result_file, 'rb') as in_file:\n- expected_results = pickle.load(in_file)\n+ # with open(result_file, 'rb') as in_file:\n+ # expected_results = pickle.load(in_file)\n- assert results.seed == expected_results.seed\n+ # assert results.seed == expected_results.seed\ndef test_run_reaction_ko_multi_objective_benchmark(self, benchmark, reaction_ko_multi_objective):\nbenchmark(reaction_ko_multi_objective.run, max_evaluations=3000, pop_size=10, view=SequentialView(), seed=SEED)\n@@ -1070,13 +1070,13 @@ class TestGeneKnockoutOptimization:\nassert len(results.data_frame.targets) == len(results.data_frame.targets.apply(tuple).unique())\n- with open(result_file, 'wb') as in_file:\n- pickle.dump(results, in_file)\n+ # with open(result_file, 'wb') as in_file:\n+ # pickle.dump(results, in_file)\n- with open(result_file, 'rb') as in_file:\n- expected_results = pickle.load(in_file)\n+ # with open(result_file, 'rb') as in_file:\n+ # expected_results = pickle.load(in_file)\n- assert results.seed == expected_results.seed\n+ # assert results.seed == expected_results.seed\ndef test_run_gene_ko_multi_objective_benchmark(self, gene_ko_multi_objective, benchmark):\nbenchmark(gene_ko_multi_objective.run, max_evaluations=3000, pop_size=10, view=SequentialView(), seed=SEED)\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | Skip more pickle problems |
89,741 | 12.10.2021 16:24:27 | -7,200 | 094c7d659d64f08242e97e71440e023c32d0bca8 | chore: use official pypi GH action and pypi API token | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/main.yml",
"new_path": ".github/workflows/main.yml",
"diff": "@@ -61,28 +61,12 @@ jobs:\npython-version: [3.8]\nsteps:\n- - uses: actions/checkout@v2\n- - name: Set up Python ${{ matrix.python-version }}\n- uses: actions/setup-python@v2\n+ - name: Publish package\n+ if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags')\n+ uses: pypa/gh-action-pypi-publish@release/v1\nwith:\n- python-version: ${{ matrix.python-version }}\n- - name: Get tag\n- id: tag\n- run: echo \"::set-output name=version::${GITHUB_REF#refs/tags/}\"\n- - name: Install dependencies\n- run: |\n- python -m pip install --upgrade pip setuptools wheel\n- python -m pip install twine\n- - name: Build package\n- run: python setup.py sdist bdist_wheel\n- - name: Check the package\n- run: twine check dist/*\n- - name: Publish to PyPI\n- env:\n- TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}\n- TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}\n- run:\n- twine upload --verbose -u TWINE_USERNAME -p TWINE_PASSWORD --skip-existing --non-interactive dist/*\n+ user: __token__\n+ password: ${{ secrets.PYPI_API_TOKEN }}\n- name: Create GitHub release\nuses: actions/create-release@v1\nenv:\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | chore: use official pypi GH action and pypi API token |
89,741 | 12.10.2021 16:58:47 | -7,200 | 3cd7fd0be5236e3d6bfd32e7101cbaa1509c41a9 | chore: don't forget to build package before deploying it | [
{
"change_type": "MODIFY",
"old_path": ".github/workflows/main.yml",
"new_path": ".github/workflows/main.yml",
"diff": "@@ -61,6 +61,22 @@ jobs:\npython-version: [3.8]\nsteps:\n+ - uses: actions/checkout@v2\n+ - name: Set up Python ${{ matrix.python-version }}\n+ uses: actions/setup-python@v2\n+ with:\n+ python-version: ${{ matrix.python-version }}\n+ - name: Get tag\n+ id: tag\n+ run: echo \"::set-output name=version::${GITHUB_REF#refs/tags/}\"\n+ - name: Install dependencies\n+ run: |\n+ python -m pip install --upgrade pip setuptools wheel\n+ python -m pip install twine\n+ - name: Build package\n+ run: python setup.py sdist bdist_wheel\n+ - name: Check the package\n+ run: twine check dist/*\n- name: Publish package\nif: github.event_name == 'push' && startsWith(github.ref, 'refs/tags')\nuses: pypa/gh-action-pypi-publish@release/v1\n"
}
] | Python | Apache License 2.0 | biosustain/cameo | chore: don't forget to build package before deploying it |
748,240 | 09.04.2017 08:22:09 | 14,400 | c5bb6bf450a06ad13982d85989af803d1398abdc | Fixed some issues with entity id and blacklist filters | [
{
"change_type": "MODIFY",
"old_path": "server-events/server-events.html",
"new_path": "server-events/server-events.html",
"diff": "<script type=\"text/javascript\">\n// TODO: Add an option to only output changes in state (ie, state on, state on === no msg emitted)\n// TODO: Add a node that passes state messages along, and if X time passes without state changing send event?\n- RED.nodes.registerType('events-state-changed', {\n+ RED.nodes.registerType('server-events', {\ncategory: 'home_assistant',\ncolor: '#038FC7',\ndefaults: {\ninputs: 0,\noutputs: 1,\nicon: \"arrow-in.png\",\n- label: function() { return (this.name) ? `Events: ${this.name}` : `Events: ${this.eventtypefilter}:${this.eventidfilter || 'all'}`},\n+ label: function() { return (this.name) ? `HA Events: ${this.name}` : `HA Events: ${this.eventtypefilter}:${this.entityidfilter || 'all'}`},\noneditprepare: function() {\n// TODO: How to get list of events that were fetched from HA\n// into the UI side? Server is id below\n</script>\n-<script type=\"text/x-red\" data-template-name=\"events-state-changed\">\n+<script type=\"text/x-red\" data-template-name=\"server-events\">\n<div class=\"form-row\">\n<label for=\"node-input-name\"><i class=\"fa fa-tag\"></i> Name</label>\n<input type=\"text\" id=\"node-input-name\" placeholder=\"Name\">\n<div class=\"form-row\">\n<label for=\"node-input-entityidblacklist\"><i class=\"fa fa-dot-circle-o\"></i> EntityID Blacklist</label>\n- <input type=\"text\" id=\"node-input-entityidblacklist\" placeholder=\"sensor.time,sensor.date__time,dark_sky,sun.sun\" />\n+ <input type=\"text\" id=\"node-input-entityidblacklist\" />\n</div>\n<div class=\"form-row\">\n<label> </label>\n<input type=\"checkbox\" id=\"node-input-skipnochange\" style=\"display: inline-block; width: auto; vertical-align: top;\">\n- <label for=\"node-input-skipnochange\" style=\"width: 80%;\"> Exclude Duplicate States</label>\n+ <label for=\"node-input-skipnochange\" style=\"width: 90%;\"> Exclude Duplicate States</label>\n</div>\n</script>\n-<script type=\"text/x-red\" data-help-name=\"events-state-changed\">\n+<script type=\"text/x-red\" data-help-name=\"server-events\">\n<p>Outputs events received from the home assistant server.</p>\n<p>NOTE: The filters are simple substring matches, you can add multiple by comma seperated list</p>\n<br/>\n"
},
{
"change_type": "MODIFY",
"old_path": "server-events/server-events.js",
"new_path": "server-events/server-events.js",
"diff": "@@ -25,10 +25,10 @@ const incomingEvents = {\n}\nreturn shouldSkip;\n},\n- shouldExcludeEvent: function shouldExcludeEvent(entityId, { entityIdFilter, entityIdBlacklist }) {\n+ shouldIncludeEvent: function shouldIncludeEvent(entityId, { entityIdFilter, entityIdBlacklist }) {\nconst findings = {};\n// If include filter is null then set to found\n- if (!entityIdFilter) { findings.includeFound = true; }\n+ if (!entityIdFilter) { findings.included = true; }\nif (entityIdFilter && entityIdFilter.length) {\nconst found = entityIdFilter.filter(iStr => (entityId.indexOf(iStr) >= 0));\n@@ -36,14 +36,14 @@ const incomingEvents = {\n}\n// If include filter is null then set to found\n- if (!entityIdBlacklist) { findings.excludeFound = false; }\n+ if (!entityIdBlacklist) { findings.excluded = false; }\nif (entityIdBlacklist && entityIdBlacklist.length) {\nconst found = entityIdBlacklist.filter(blStr => (entityId.indexOf(blStr) >= 0));\nfindings.excluded = (found.length > 0);\n}\n- return !findings.included && findings.excluded;\n+ return findings.included && !findings.excluded;\n},\n/* eslint-disable consistent-return */\nonIncomingMessage: function onIncomingMessage(evt, node) {\n@@ -64,11 +64,11 @@ const incomingEvents = {\nif (!node.settings.entityIdFilter && !node.settings.entityIdBlacklist) {\nnode.send(msg);\n// If include or blacklist do not send if filtered\n- } else if (incomingEvents.shouldExcludeEvent(entity_id, node.settings)) {\n- debug('Skipping event due to include or blacklist filter');\n+ } else if (incomingEvents.shouldIncludeEvent(entity_id, node.settings)) {\n+ node.send(msg);\n// Sending because filter check passed\n} else {\n- node.send(msg);\n+ debug('Skipping event due to include or blacklist filter');\n}\n}\n}\n@@ -98,5 +98,5 @@ module.exports = function(RED) {\n}\n}\n- RED.nodes.registerType('events-state-changed', EventsStateChange);\n+ RED.nodes.registerType('server-events', EventsStateChange);\n};\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Fixed some issues with entity id and blacklist filters |
748,240 | 09.04.2017 08:23:04 | 14,400 | 0fb53f54b88ec00baf272c973e47d83a6b4d49d2 | Bumped node-home-assistant version | [
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "},\n\"dependencies\": {\n\"debug\": \"^2.6.3\",\n- \"node-home-assistant\": \"^0.0.2\"\n+ \"node-home-assistant\": \"0.0.3\"\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "yarn.lock",
"new_path": "yarn.lock",
"diff": "@@ -8,12 +8,6 @@ axios@^0.15.3:\ndependencies:\nfollow-redirects \"1.0.0\"\n-axios@^0.16.0:\n- version \"0.16.0\"\n- resolved \"https://registry.yarnpkg.com/axios/-/axios-0.16.0.tgz#6ed9771d815f429e7510f2838262957c4953d3b6\"\n- dependencies:\n- follow-redirects \"1.0.0\"\n-\ndebug@^2.2.0, debug@^2.6.3:\nversion \"2.6.3\"\nresolved \"https://registry.yarnpkg.com/debug/-/debug-2.6.3.tgz#0f7eb8c30965ec08c72accfa0130c8b79984141d\"\n@@ -36,9 +30,9 @@ [email protected]:\nversion \"0.7.2\"\nresolved \"https://registry.yarnpkg.com/ms/-/ms-0.7.2.tgz#ae25cf2512b3885a1d95d7f037868d8431124765\"\n-node-home-assistant@^0.0.2:\n- version \"0.0.2\"\n- resolved \"https://registry.yarnpkg.com/node-home-assistant/-/node-home-assistant-0.0.2.tgz#b7da535049dde137022fdf72d6fa6c5e499c9d56\"\[email protected]:\n+ version \"0.0.3\"\n+ resolved \"https://registry.yarnpkg.com/node-home-assistant/-/node-home-assistant-0.0.3.tgz#f33afe2bd48203506b02ace1617ea540ae625448\"\ndependencies:\naxios \"^0.15.3\"\ndebug \"^2.6.3\"\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Bumped node-home-assistant version |
748,240 | 12.04.2017 20:33:38 | 14,400 | 5e5c4337aee604285e4a51868c1eb96c98a19360 | Added 'current state' node | [
{
"change_type": "RENAME",
"old_path": "server/server.html",
"new_path": "config-server/config-server.html",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "server/server.js",
"new_path": "config-server/config-server.js",
"diff": "@@ -25,6 +25,8 @@ module.exports = function(RED) {\nnode.availableServices = ha.availableServices;\nnode.availableEvents = ha.availableEvents;\n}\n+\n+\n}\nRED.nodes.registerType('server', ConfigServer);\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "node-current-state/node-current-state.html",
"diff": "+<script type=\"text/x-red\" data-template-name=\"current-state\">\n+ <div class=\"form-row\">\n+ <label for=\"node-input-name\"><i class=\"fa fa-tag\"></i> Name</label>\n+ <input type=\"text\" id=\"node-input-name\" placeholder=\"Name\">\n+ </div>\n+ <!--<div class=\"form-tips\"><b>Tip:</b> This is here to help.</div>-->\n+\n+ <div class=\"form-row\">\n+ <label for=\"node-input-server\"><i class=\"fa fa-dot-circle-o\"></i> Server</label>\n+ <input type=\"text\" id=\"node-input-server\" />\n+ </div>\n+\n+ <div class=\"form-row\">\n+ <label for=\"node-input-entityid\"><i class=\"fa fa-dot-circle-o\"></i> Entity ID</label>\n+ <input type=\"text\" id=\"node-input-entityid\" placeholder=\"light\"/>\n+ </div>\n+\n+</script>\n+\n+<script type=\"text/x-red\" data-help-name=\"current-state\">\n+ <p>Current state of an Entity</p>\n+ <p>Uses the nodes config entity id setting, if set, and outputs the current state of that entity</p>\n+ <p>If the incoming message has a `payload` property with `entity_id` set it will override the config value and output that entities state</p>\n+ <p>All other `msg.payload` properties are ignored</p>\n+ <p> NOTE: Entity ID must be set, either through config or from incoming message, if not set then nothing will be outputed</p>\n+</script>\n+\n+<script type=\"text/javascript\">\n+ RED.nodes.registerType('current-state', {\n+ category: 'home_assistant',\n+ color: '#52C0F2',\n+ defaults: {\n+ name: { value: '' },\n+ server: { value: '', type: 'server' },\n+ entityid: { value: '' }\n+ },\n+ inputs: 1,\n+ outputs: 1,\n+ icon: \"arrow-out.png\",\n+ label: function() { return this.name ? `Get State: ${this.name}` : `Get State`; }\n+ });\n+</script>\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "node-current-state/node-current-state.js",
"diff": "+'use strict';\n+const debug = require('debug')('ha-eventer:current-state');\n+\n+const _int = {\n+ getSettings: function(config) {\n+ return {\n+ entity_id: config.entityid\n+ };\n+ },\n+ onInput: function(msg, node) {\n+ const entityId = (msg.payload && msg.payload.entity_id)\n+ ? msg.payload.entity_id\n+ : node.settings.entity_id;\n+\n+ if (!entityId) {\n+ node.warn('Entity ID not set, no state to output');\n+ } else {\n+ const currentState = node.server.homeAssistant.states[entityId];\n+ if (!currentState) { node.warn(`State not found for entity_id: ${entityId}`); }\n+ else { node.send({ payload: currentState }); }\n+ }\n+ }\n+};\n+\n+\n+module.exports = function(RED) {\n+ function CurrentState(config) {\n+ const node = this;\n+ RED.nodes.createNode(this, config);\n+ node.server = RED.nodes.getNode(config.server);\n+ node.settings = _int.getSettings(config);\n+\n+ node.on('input', (msg) => _int.onInput(msg, node));\n+ }\n+\n+ RED.nodes.registerType('current-state', CurrentState);\n+}\n"
},
{
"change_type": "RENAME",
"old_path": "server-events/server-events.html",
"new_path": "node-server-events/node-server-events.html",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "server-events/server-events.js",
"new_path": "node-server-events/node-server-events.js",
"diff": "@@ -20,9 +20,8 @@ const incomingEvents = {\nif (!node.settings.skipNoChange) { return false; }\nif (!e.event || !e.event.old_state || !e.event.new_state) { return false; }\nconst shouldSkip = (e.event.old_state.state === e.event.new_state.state);\n- if (shouldSkip) {\n- debug('Skipping event, state unchanged new vs. old');\n- }\n+\n+ if (shouldSkip) { debug('Skipping event, state unchanged new vs. old'); }\nreturn shouldSkip;\n},\nshouldIncludeEvent: function shouldIncludeEvent(entityId, { entityIdFilter, entityIdBlacklist }) {\n"
},
{
"change_type": "RENAME",
"old_path": "service-call/service-call.html",
"new_path": "node-service-call/node-service-call.html",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "service-call/service-call.js",
"new_path": "node-service-call/node-service-call.js",
"diff": ""
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "],\n\"node-red\": {\n\"nodes\": {\n- \"server\": \"server/server.js\",\n- \"server-events\": \"server-events/server-events.js\",\n- \"service-call\": \"service-call/service-call.js\"\n+ \"server\": \"config-server/config-server.js\",\n+ \"server-events\": \"node-server-events/node-server-events.js\",\n+ \"service-call\": \"node-service-call/node-service-call.js\",\n+ \"current-state\": \"node-current-state/node-current-state.js\"\n}\n},\n\"dependencies\": {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Added 'current state' node |
748,240 | 12.04.2017 21:44:35 | 14,400 | 364c5c23af993993cd621ed049577b87da8f1c94 | Allow for halting a flow with current-state node | [
{
"change_type": "MODIFY",
"old_path": "node-current-state/node-current-state.html",
"new_path": "node-current-state/node-current-state.html",
"diff": "<div class=\"form-row\">\n<label for=\"node-input-entityid\"><i class=\"fa fa-dot-circle-o\"></i> Entity ID</label>\n- <input type=\"text\" id=\"node-input-entityid\" placeholder=\"light\"/>\n+ <input type=\"text\" id=\"node-input-entityid\" placeholder=\"light.livingroom_light\"/>\n+ </div>\n+\n+ <div class=\"form-row\">\n+ <label for=\"node-input-haltif\"><i class=\"fa fa-dot-circle-o\"></i> Halt If</label>\n+ <input type=\"text\" id=\"node-input-haltif\" placeholder=\"off\"/>\n</div>\n</script>\n<p>Uses the nodes config entity id setting, if set, and outputs the current state of that entity</p>\n<p>If the incoming message has a `payload` property with `entity_id` set it will override the config value and output that entities state</p>\n<p>All other `msg.payload` properties are ignored</p>\n+ <p>The 'Halt If' value will stop the current flow if the entities state === this value.\n+ For instance, you could get the state of an 'input_boolean' switch from home assistant and set 'Half If' to \"off\" which would cause\n+ the flow execution to stop unless that input_boolean was 'turned on' within home assistant</p>\n<p> NOTE: Entity ID must be set, either through config or from incoming message, if not set then nothing will be outputed</p>\n</script>\ndefaults: {\nname: { value: '' },\nserver: { value: '', type: 'server' },\n- entityid: { value: '' }\n+ entityid: { value: '' },\n+ haltif: { value: '' }\n},\ninputs: 1,\noutputs: 1,\n"
},
{
"change_type": "MODIFY",
"old_path": "node-current-state/node-current-state.js",
"new_path": "node-current-state/node-current-state.js",
"diff": "@@ -4,7 +4,8 @@ const debug = require('debug')('ha-eventer:current-state');\nconst _int = {\ngetSettings: function(config) {\nreturn {\n- entity_id: config.entityid\n+ entity_id: config.entityid,\n+ haltIf: config.haltif\n};\n},\nonInput: function(msg, node) {\n@@ -16,8 +17,16 @@ const _int = {\nnode.warn('Entity ID not set, no state to output');\n} else {\nconst currentState = node.server.homeAssistant.states[entityId];\n- if (!currentState) { node.warn(`State not found for entity_id: ${entityId}`); }\n+ if (!currentState) {\n+ node.warn(`State not found for entity_id: ${entityId}`);\n+ // Stop the flow execution if 'halt if' setting is set and true\n+ } else if (node.settings.haltIf) {\n+ if (currentState.state === node.settings.haltIf) { node.log('Halting flow, current state === haltIf setting'); }\nelse { node.send({ payload: currentState }); }\n+ // Else just send on\n+ } else {\n+ node.send({ payload: currentState });\n+ }\n}\n}\n};\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Allow for halting a flow with current-state node |
748,240 | 14.04.2017 07:54:51 | 14,400 | 5025ae2b31956ac72f814270a86b483cf6897dc3 | Moar features | [
{
"change_type": "MODIFY",
"old_path": "node-current-state/node-current-state.html",
"new_path": "node-current-state/node-current-state.html",
"diff": "<label for=\"node-input-name\"><i class=\"fa fa-tag\"></i> Name</label>\n<input type=\"text\" id=\"node-input-name\" placeholder=\"Name\">\n</div>\n- <!--<div class=\"form-tips\"><b>Tip:</b> This is here to help.</div>-->\n<div class=\"form-row\">\n<label for=\"node-input-server\"><i class=\"fa fa-dot-circle-o\"></i> Server</label>\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-events/node-server-events.html",
"new_path": "node-server-events/node-server-events.html",
"diff": "<script type=\"text/javascript\">\n- // TODO: Add an option to only output changes in state (ie, state on, state on === no msg emitted)\n- // TODO: Add a node that passes state messages along, and if X time passes without state changing send event?\nRED.nodes.registerType('server-events', {\ncategory: 'home_assistant',\ncolor: '#038FC7',\ndefaults: {\nname: { value: '' },\n- // TODO: Set as credentials http://nodered.org/docs/creating-nodes/credentials\nserver: { value: '', type: 'server' },\n- eventtypefilter: { value: 'state_changed', required: true },\n- entityidfilter: { value: '', },\n- entityidblacklist: { value: 'sensor.time,sensor.date__time,dark_sky,sun.sun' },\n- skipnochange: { value: true }\n+ eventtypefilter: { value: 'all', required: true },\n},\ninputs: 0,\noutputs: 1,\nicon: \"arrow-in.png\",\n- label: function() { return (this.name) ? `HA Events: ${this.name}` : `HA Events: ${this.eventtypefilter}:${this.entityidfilter || 'all'}`},\n+ label: function() { return (this.name) ? `HA Events: ${this.name}` : `HA Events: ${this.eventtypefilter}`},\noneditprepare: function() {\n// TODO: How to get list of events that were fetched from HA\n// into the UI side? Server is id below\n<label for=\"node-input-name\"><i class=\"fa fa-tag\"></i> Name</label>\n<input type=\"text\" id=\"node-input-name\" placeholder=\"Name\">\n</div>\n- <!--<div class=\"form-tips\"><b>Tip:</b> This is here to help.</div>-->\n<div class=\"form-row\">\n<label for=\"node-input-server\"><i class=\"fa fa-dot-circle-o\"></i> Server</label>\n<div class=\"form-row\">\n<label for=\"node-input-eventtypefilter\"><i class=\"fa fa-tag\"></i> EventType Filter</label>\n<select type=\"text\" id=\"node-input-eventtypefilter\" style=\"width:72%;\" id=\"node-input-eventtypefilter\">\n- <option selected value=\"state_changed\">state_changed</option>\n- <option value=\"all\">all</option>\n+ <option selected value=\"all\">all</option>\n+ <option value=\"state_changed\">state_changed</option>\n</select>\n</div>\n-\n- <div class=\"form-row\">\n- <label for=\"node-input-entityidfilter\"><i class=\"fa fa-dot-circle-o\"></i> EntityID Filter</label>\n- <input type=\"text\" id=\"node-input-entityidfilter\" placeholder=\"binary_sensor\"/>\n- </div>\n-\n- <div class=\"form-row\">\n- <label for=\"node-input-entityidblacklist\"><i class=\"fa fa-dot-circle-o\"></i> EntityID Blacklist</label>\n- <input type=\"text\" id=\"node-input-entityidblacklist\" />\n- </div>\n-\n- <div class=\"form-row\">\n- <label> </label>\n- <input type=\"checkbox\" id=\"node-input-skipnochange\" style=\"display: inline-block; width: auto; vertical-align: top;\">\n- <label for=\"node-input-skipnochange\" style=\"width: 90%;\"> Exclude Duplicate States</label>\n- </div>\n</script>\n<script type=\"text/x-red\" data-help-name=\"server-events\">\n<p>NOTE: The filters are simple substring matches, you can add multiple by comma seperated list</p>\n<br/>\n<p>Event Type Filter: Only events that subtring match event_type field</p>\n- <p>Entity ID Filter: Only events that subtring match entity_id field</p>\n- <p>Entity ID Blacklist: Exclude events that substring match entity_id</p>\n- <p>By default will exclude events if (oldstate === newstate)</p>\n<p>The outputted message object contains the following data, underscored values are straight from home assistant</p>\n<table style=\"width: 100%;\" border=\"1\" cellpadding=\"10\">\n<tbody>\n+ <tr> <td>topic</td> <td>event_type</td> </tr>\n+ <tr> <td>payload</td> <td>original event</td> </tr>\n<tr> <td>event_type</td> <td>event_type</td> </tr>\n- <tr> <td>entity_id</td> <td>entity_id || null</td> </tr>\n- <tr> <td>topic</td> <td>event_type:entity_id || event_type</td> </tr>\n- <tr> <td>payload</td> <td>event.new_state.state || original event</td> </tr>\n- <tr> <td>event</td> <td>Original event</td> </tr>\n</tbody>\n</table>\n</script>\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-events/node-server-events.js",
"new_path": "node-server-events/node-server-events.js",
"diff": "@@ -4,10 +4,7 @@ const debug = require('debug')('ha-eventer:server-events');\nconst incomingEvents = {\ngetSettings: function getSettings(config) {\nconst settings = {\n- eventTypeFilter: config.eventtypefilter,\n- entityIdFilter: config.entityidfilter ? config.entityidfilter.split(',').map(f => f.trim()) : null,\n- entityIdBlacklist: config.entityidblacklist ? config.entityidblacklist.split(',').map(f => f.trim()) : null,\n- skipNoChange: config.skipnochange\n+ eventTypeFilter: config.eventtypefilter\n};\nreturn settings;\n@@ -15,64 +12,9 @@ const incomingEvents = {\nsetStatus: function setStatus(isConnected, node) {\nif (isConnected) { node.status({ fill: 'green', shape: 'ring', text: 'Connected' }); }\nelse { node.status({ fill: 'red', shape: 'ring', text: 'Disconnected' }) }\n- },\n- shouldSkipEvent: function shouldSkipEvent(e, node) {\n- if (!node.settings.skipNoChange) { return false; }\n- if (!e.event || !e.event.old_state || !e.event.new_state) { return false; }\n- const shouldSkip = (e.event.old_state.state === e.event.new_state.state);\n-\n- if (shouldSkip) { debug('Skipping event, state unchanged new vs. old'); }\n- return shouldSkip;\n- },\n- shouldIncludeEvent: function shouldIncludeEvent(entityId, { entityIdFilter, entityIdBlacklist }) {\n- const findings = {};\n- // If include filter is null then set to found\n- if (!entityIdFilter) { findings.included = true; }\n-\n- if (entityIdFilter && entityIdFilter.length) {\n- const found = entityIdFilter.filter(iStr => (entityId.indexOf(iStr) >= 0));\n- findings.included = (found.length > 0);\n}\n-\n- // If include filter is null then set to found\n- if (!entityIdBlacklist) { findings.excluded = false; }\n-\n- if (entityIdBlacklist && entityIdBlacklist.length) {\n- const found = entityIdBlacklist.filter(blStr => (entityId.indexOf(blStr) >= 0));\n- findings.excluded = (found.length > 0);\n- }\n-\n- return findings.included && !findings.excluded;\n- },\n- /* eslint-disable consistent-return */\n- onIncomingMessage: function onIncomingMessage(evt, node) {\n- if (incomingEvents.shouldSkipEvent(evt, node)) { return null; }\n-\n- const isStateChangedListener = (node.settings.eventTypeFilter === 'state_changed');\n-\n- const { event_type, entity_id, event } = evt;\n- const msg = {\n- event_type: event_type,\n- entity_id: entity_id,\n- topic: (entity_id) ? `${event_type}:${entity_id}` : event_type,\n- payload: (isStateChangedListener) ? event.new_state.state : event,\n- event: event\n};\n- // If no filters just send\n- if (!node.settings.entityIdFilter && !node.settings.entityIdBlacklist) {\n- node.send(msg);\n- // If include or blacklist do not send if filtered\n- } else if (incomingEvents.shouldIncludeEvent(entity_id, node.settings)) {\n- node.send(msg);\n- // Sending because filter check passed\n- } else {\n- debug('Skipping event due to include or blacklist filter');\n- }\n- }\n-}\n-\n-\nmodule.exports = function(RED) {\nfunction EventsStateChange(config) {\n@@ -86,14 +28,17 @@ module.exports = function(RED) {\n// If the eventsource was setup start listening for events\nif (node.server) {\nif (node.server.connected) { incomingEvents.setStatus(true, node); }\n-\nconst eventsClient = node.server.events;\n- // Will eitner be events_state_changed, events_all, or events_<some other ha event>\n- eventsClient.on(`ha_events:${node.settings.eventTypeFilter}`, (evt) => incomingEvents.onIncomingMessage(evt, node));\n+ eventsClient.on(`ha_events:${node.settings.eventTypeFilter}`, (evt) => {\n+ node.send({ event_type: evt.event_type, topic: evt.event_type, payload: evt});\n+ });\neventsClient.on('ha_events:close', () => incomingEvents.setStatus(false, node));\neventsClient.on('ha_events:open', () => incomingEvents.setStatus(true, node));\n- eventsClient.on('ha_events:error', (err) => node.warn(err));\n+ eventsClient.on('ha_events:error', (err) => {\n+ incomingEvents.setStatus(false, node);\n+ node.warn(err);\n+ });\n}\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "node-server-state-changed/node-server-state-changed.html",
"diff": "+<script type=\"text/javascript\">\n+ RED.nodes.registerType('server-state-changed', {\n+ category: 'home_assistant',\n+ color: '#038FC7',\n+ defaults: {\n+ name: { value: '' },\n+ server: { value: '', type: 'server' },\n+ entityidfilter: { value: '' },\n+ entityidblacklist: { value: 'sensor.time,sensor.date__time,dark_sky,sun.sun' },\n+ skipifstate: { value: '' }\n+ },\n+ inputs: 0,\n+ outputs: 1,\n+ icon: \"arrow-in.png\",\n+ label: function() { return (this.name) ? `HA State Changed: ${this.name}` : `HA State Changed: ${this.entityidfilter || 'all'}`}\n+ });\n+</script>\n+\n+\n+<script type=\"text/x-red\" data-template-name=\"server-state-changed\">\n+ <div class=\"form-row\">\n+ <label for=\"node-input-name\"><i class=\"fa fa-tag\"></i> Name</label>\n+ <input type=\"text\" id=\"node-input-name\" placeholder=\"Name\">\n+ </div>\n+\n+ <div class=\"form-row\">\n+ <label for=\"node-input-server\"><i class=\"fa fa-dot-circle-o\"></i> Server</label>\n+ <input type=\"text\" id=\"node-input-server\" />\n+ </div>\n+\n+ <div class=\"form-row\">\n+ <label for=\"node-input-entityidfilter\"><i class=\"fa fa-dot-circle-o\"></i> EntityID Filter</label>\n+ <input type=\"text\" id=\"node-input-entityidfilter\" placeholder=\"binary_sensor\"/>\n+ </div>\n+\n+ <div class=\"form-row\">\n+ <label for=\"node-input-entityidblacklist\"><i class=\"fa fa-dot-circle-o\"></i> EntityID Blacklist</label>\n+ <input type=\"text\" id=\"node-input-entityidblacklist\" />\n+ </div>\n+\n+ <div class=\"form-row\">\n+ <label for=\"node-input-skipifstate\"><i class=\"fa fa-dot-circle-o\"></i> Skip If State</label>\n+ <input type=\"text\" id=\"node-input-skipifstate\" />\n+ </div>\n+\n+</script>\n+\n+<script type=\"text/x-red\" data-help-name=\"server-state-changed\">\n+ <p>Outputs 'state_changed' event types sent from Home Assistant</p>\n+ <p>NOTE: The filters are simple substring matches, you can add multiple by comma seperated list and each entry will be matched separately</p>\n+ <br/>\n+ <p>Entity ID Filter: Only state changes that subtring match entity_id field</p>\n+ <p>Entity ID Blacklist: Exclude state changes that substring match entity_id</p>\n+ <p>Skip If State: If the new_state === this setting then do -not- send the event</p>\n+\n+ <p>The outputted message object contains the following data, underscored values are straight from home assistant</p>\n+ <table style=\"width: 100%;\" border=\"1\" cellpadding=\"10\">\n+ <tbody>\n+ <tr> <td>topic</td> <td>entity_id</td> </tr>\n+ <tr> <td>payload</td> <td>event.new_state.state</td> </tr>\n+ <tr> <td>event</td> <td>original event object</td> </tr>\n+ </tbody>\n+ </table>\n+</script>\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "node-server-state-changed/node-server-state-changed.js",
"diff": "+'use strict';\n+const debug = require('debug')('ha-eventer:server-state-changed');\n+\n+const incomingEvents = {\n+ getSettings: function getSettings(config) {\n+ const settings = {\n+ entityIdFilter: config.entityidfilter ? config.entityidfilter.split(',').map(f => f.trim()) : null,\n+ entityIdBlacklist: config.entityidblacklist ? config.entityidblacklist.split(',').map(f => f.trim()) : null,\n+ skipIfState: config.skipifstate\n+ };\n+\n+ return settings;\n+ },\n+ setStatus: function setStatus(isConnected, node) {\n+ if (isConnected) { node.status({ fill: 'green', shape: 'ring', text: 'Connected' }); }\n+ else { node.status({ fill: 'red', shape: 'ring', text: 'Disconnected' }) }\n+ },\n+ shouldSkipNoChange: function shouldSkipNoChange(e, node) {\n+ if (!e.event || !e.event.old_state || !e.event.new_state) { return false; }\n+ const shouldSkip = (e.event.old_state.state === e.event.new_state.state);\n+\n+ if (shouldSkip) { debug('Skipping event, state unchanged new vs. old'); }\n+ return shouldSkip;\n+ },\n+ shouldSkipIfState: function shouldSkipIfState(e, skipIfState) {\n+ if (!skipIfState) { return false; }\n+ const shouldSkip = (skipIfState === e.event.new_state.state);\n+ if (shouldSkip) { debug('Skipping event, incoming event state === skipIfState setting'); }\n+ return shouldSkip;\n+ },\n+ shouldIncludeEvent: function shouldIncludeEvent(entityId, { entityIdFilter, entityIdBlacklist }) {\n+ // If neither filter is sent just send the event on\n+ if (!entityIdFilter && !entityIdBlacklist) { return true; }\n+\n+ const findings = {};\n+ // If include filter is null then set to found\n+ if (!entityIdFilter) { findings.included = true; }\n+\n+ if (entityIdFilter && entityIdFilter.length) {\n+ const found = entityIdFilter.filter(iStr => (entityId.indexOf(iStr) >= 0));\n+ findings.included = (found.length > 0);\n+ }\n+\n+ // If blacklist is null set exluded false\n+ if (!entityIdBlacklist) { findings.excluded = false; }\n+\n+ if (entityIdBlacklist && entityIdBlacklist.length) {\n+ const found = entityIdBlacklist.filter(blStr => (entityId.indexOf(blStr) >= 0));\n+ findings.excluded = (found.length > 0);\n+ }\n+\n+ return findings.included && !findings.excluded;\n+ },\n+ /* eslint-disable consistent-return */\n+ onIncomingMessage: function onIncomingMessage(evt, node) {\n+ if (incomingEvents.shouldSkipNoChange(evt, node)) { return null; }\n+ if (incomingEvents.shouldSkipIfState(evt, node.settings.skipIfState)) { return null; }\n+\n+ const { entity_id, event } = evt;\n+ const msg = {\n+ topic: entity_id,\n+ payload: event.new_state.state,\n+ event: event\n+ };\n+\n+ if (incomingEvents.shouldIncludeEvent(entity_id, node.settings)) {\n+ node.send(msg);\n+ } else {\n+ debug('Skipping event due to include or blacklist filter');\n+ }\n+ }\n+}\n+\n+\n+\n+module.exports = function(RED) {\n+ function EventsStateChange(config) {\n+ RED.nodes.createNode(this, config);\n+ const node = this;\n+ node.settings = incomingEvents.getSettings(config);\n+\n+ node.server = RED.nodes.getNode(config.server);\n+ incomingEvents.setStatus(false, node);\n+\n+ // If the eventsource was setup start listening for events\n+ if (node.server) {\n+ if (node.server.connected) { incomingEvents.setStatus(true, node); }\n+ const eventsClient = node.server.events;\n+\n+ eventsClient.on('ha_events:state_changed', (evt) => incomingEvents.onIncomingMessage(evt, node));\n+ eventsClient.on('ha_events:close', () => incomingEvents.setStatus(false, node));\n+ eventsClient.on('ha_events:open', () => incomingEvents.setStatus(true, node));\n+ eventsClient.on('ha_events:error', (err) => {\n+ incomingEvents.setStatus(false, node);\n+ node.warn(err);\n+ });\n+ }\n+ }\n+\n+ RED.nodes.registerType('server-state-changed', EventsStateChange);\n+};\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"nodes\": {\n\"server\": \"config-server/config-server.js\",\n\"server-events\": \"node-server-events/node-server-events.js\",\n+ \"server-state-changed\": \"node-server-state-changed/node-server-state-changed.js\",\n\"service-call\": \"node-service-call/node-service-call.js\",\n\"current-state\": \"node-current-state/node-current-state.js\"\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Moar features |
748,240 | 15.04.2017 00:07:47 | 14,400 | c088279e8e9dd92b592896068d0ddd9f680acc50 | Added some placeholder icons, adjusted palette naming for better fit visually | [
{
"change_type": "MODIFY",
"old_path": "config-server/config-server.html",
"new_path": "config-server/config-server.html",
"diff": "+<script type=\"text/javascript\">\n+ RED.nodes.registerType('server', {\n+ category: 'config',\n+ defaults: {\n+ name: { value: '', required: false },\n+ // TODO: Set as credentials http://nodered.org/docs/creating-nodes/credentials\n+ url: { value: '', required: true },\n+ pass: { value: '', required: false }\n+ },\n+ icon: \"home.png\",\n+ label: function() { return this.name || this.url || 'Home Assistant'; },\n+ oneditprepare: function() {\n+ console.dir(this);\n+ }\n+ });\n+</script>\n+\n+\n<script type=\"text/x-red\" data-template-name=\"server\">\n<div class=\"form-row\">\n<label for=\"node-config-input-url\"><i class=\"fa fa-dot-circle-o\"></i> Base URL</label>\n<script type=\"text/x-red\" data-help-name=\"server\">\n<p>Home Assistant connection configuration</p>\n</script>\n-\n-<script type=\"text/javascript\">\n- RED.nodes.registerType('server', {\n- category: 'config',\n- defaults: {\n- // name: { value: '', required: false },\n- // TODO: Set as credentials http://nodered.org/docs/creating-nodes/credentials\n- url: { value: '', required: true },\n- pass: { value: '', required: false }\n- },\n- label: function() { return this.name ? this.name : this.url || 'HA Server'; },\n- oneditprepare: function() {\n- console.dir(this);\n- }\n- });\n-</script>\n"
},
{
"change_type": "ADD",
"old_path": "config-server/icons/home.png",
"new_path": "config-server/icons/home.png",
"diff": "Binary files /dev/null and b/config-server/icons/home.png differ\n"
},
{
"change_type": "ADD",
"old_path": "node-current-state/icons/arrow-top-right.png",
"new_path": "node-current-state/icons/arrow-top-right.png",
"diff": "Binary files /dev/null and b/node-current-state/icons/arrow-top-right.png differ\n"
},
{
"change_type": "MODIFY",
"old_path": "node-current-state/node-current-state.html",
"new_path": "node-current-state/node-current-state.html",
"diff": "+<script type=\"text/javascript\">\n+ RED.nodes.registerType('current-state', {\n+ category: 'home_assistant',\n+ color: '#038FC7',\n+ defaults: {\n+ name: { value: '' },\n+ server: { value: '', type: 'server' },\n+ entityid: { value: '' },\n+ haltif: { value: '' }\n+ },\n+ inputs: 1,\n+ outputs: 1,\n+ icon: \"arrow-top-right.png\",\n+ paletteLabel: 'current state',\n+ label: function() { return this.name || `current_state:${this.entity_id}`; }\n+ });\n+</script>\n+\n<script type=\"text/x-red\" data-template-name=\"current-state\">\n<div class=\"form-row\">\n<label for=\"node-input-name\"><i class=\"fa fa-tag\"></i> Name</label>\nthe flow execution to stop unless that input_boolean was 'turned on' within home assistant</p>\n<p> NOTE: Entity ID must be set, either through config or from incoming message, if not set then nothing will be outputed</p>\n</script>\n-\n-<script type=\"text/javascript\">\n- RED.nodes.registerType('current-state', {\n- category: 'home_assistant',\n- color: '#52C0F2',\n- defaults: {\n- name: { value: '' },\n- server: { value: '', type: 'server' },\n- entityid: { value: '' },\n- haltif: { value: '' }\n- },\n- inputs: 1,\n- outputs: 1,\n- icon: \"arrow-out.png\",\n- label: function() { return this.name ? `Get State: ${this.name}` : `Get State`; }\n- });\n-</script>\n"
},
{
"change_type": "ADD",
"old_path": "node-server-events/icons/arrow-right-bold.png",
"new_path": "node-server-events/icons/arrow-right-bold.png",
"diff": "Binary files /dev/null and b/node-server-events/icons/arrow-right-bold.png differ\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-events/node-server-events.html",
"new_path": "node-server-events/node-server-events.html",
"diff": "color: '#038FC7',\ndefaults: {\nname: { value: '' },\n- server: { value: '', type: 'server' },\n- eventtypefilter: { value: 'all', required: true },\n+ server: { value: '', type: 'server' }\n},\ninputs: 0,\noutputs: 1,\n- icon: \"arrow-in.png\",\n- label: function() { return (this.name) ? `HA Events: ${this.name}` : `HA Events: ${this.eventtypefilter}`},\n- oneditprepare: function() {\n- // TODO: How to get list of events that were fetched from HA\n- // into the UI side? Server is id below\n- // Below doesn't work on UI side (getNode doesn't exist);\n- // const theServer = RED.nodes.getNode(server);\n- // const availableEventTypes = this.server.eventTypes;\n- // debugger;\n- // console.log('eventtypes');\n- // console.log(availableEventTypes);\n- // $('#node-input-eventtypefilter')\n- }\n+ icon: \"arrow-right-bold.png\",\n+ paletteLabel: 'events: all',\n+ label: function() { return this.name || `events_all: ${this.eventtypefilter}` }\n});\n</script>\n<label for=\"node-input-server\"><i class=\"fa fa-dot-circle-o\"></i> Server</label>\n<input type=\"text\" id=\"node-input-server\" />\n</div>\n-\n- <div class=\"form-row\">\n- <label for=\"node-input-eventtypefilter\"><i class=\"fa fa-tag\"></i> EventType Filter</label>\n- <select type=\"text\" id=\"node-input-eventtypefilter\" style=\"width:72%;\" id=\"node-input-eventtypefilter\">\n- <option selected value=\"all\">all</option>\n- <option value=\"state_changed\">state_changed</option>\n- </select>\n- </div>\n</script>\n<script type=\"text/x-red\" data-help-name=\"server-events\">\n<p>Outputs events received from the home assistant server.</p>\n- <p>NOTE: The filters are simple substring matches, you can add multiple by comma seperated list</p>\n- <br/>\n- <p>Event Type Filter: Only events that subtring match event_type field</p>\n<p>The outputted message object contains the following data, underscored values are straight from home assistant</p>\n<table style=\"width: 100%;\" border=\"1\" cellpadding=\"10\">\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-events/node-server-events.js",
"new_path": "node-server-events/node-server-events.js",
"diff": "@@ -3,10 +3,7 @@ const debug = require('debug')('ha-eventer:server-events');\nconst incomingEvents = {\ngetSettings: function getSettings(config) {\n- const settings = {\n- eventTypeFilter: config.eventtypefilter\n- };\n-\n+ const settings = {}\nreturn settings;\n},\nsetStatus: function setStatus(isConnected, node) {\n@@ -17,7 +14,7 @@ const incomingEvents = {\nmodule.exports = function(RED) {\n- function EventsStateChange(config) {\n+ function EventsAll(config) {\nRED.nodes.createNode(this, config);\nconst node = this;\nnode.settings = incomingEvents.getSettings(config);\n@@ -30,9 +27,10 @@ module.exports = function(RED) {\nif (node.server.connected) { incomingEvents.setStatus(true, node); }\nconst eventsClient = node.server.events;\n- eventsClient.on(`ha_events:${node.settings.eventTypeFilter}`, (evt) => {\n+ eventsClient.on('ha_events:all', (evt) => {\nnode.send({ event_type: evt.event_type, topic: evt.event_type, payload: evt});\n});\n+\neventsClient.on('ha_events:close', () => incomingEvents.setStatus(false, node));\neventsClient.on('ha_events:open', () => incomingEvents.setStatus(true, node));\neventsClient.on('ha_events:error', (err) => {\n@@ -42,5 +40,5 @@ module.exports = function(RED) {\n}\n}\n- RED.nodes.registerType('server-events', EventsStateChange);\n+ RED.nodes.registerType('server-events', EventsAll);\n};\n"
},
{
"change_type": "ADD",
"old_path": "node-server-state-changed/icons/arrow-right-bold-hexagon-outline.png",
"new_path": "node-server-state-changed/icons/arrow-right-bold-hexagon-outline.png",
"diff": "Binary files /dev/null and b/node-server-state-changed/icons/arrow-right-bold-hexagon-outline.png differ\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-state-changed/node-server-state-changed.html",
"new_path": "node-server-state-changed/node-server-state-changed.html",
"diff": "},\ninputs: 0,\noutputs: 1,\n- icon: \"arrow-in.png\",\n- label: function() { return (this.name) ? `HA State Changed: ${this.name}` : `HA State Changed: ${this.entityidfilter || 'all'}`}\n+ icon: \"arrow-right-bold-hexagon-outline.png\",\n+ paletteLabel: 'events: state',\n+ label: function() { return this.name || `state_changed: ${this.entityidfilter || 'all entities'}` }\n});\n</script>\n"
},
{
"change_type": "ADD",
"old_path": "node-service-call/icons/router-wireless.png",
"new_path": "node-service-call/icons/router-wireless.png",
"diff": "Binary files /dev/null and b/node-service-call/icons/router-wireless.png differ\n"
},
{
"change_type": "MODIFY",
"old_path": "node-service-call/node-service-call.html",
"new_path": "node-service-call/node-service-call.html",
"diff": "+<script type=\"text/javascript\">\n+ // TODO: Look for autocomplete modules to allow a select drop down (with autocomplete)\n+ // the options would be populated by the api query of services on the server node\n+\n+ RED.nodes.registerType('service-call', {\n+ category: 'home_assistant',\n+ color: '#52C0F2',\n+ // NOTE: 'domain' seems to be a nodered 'reserved' word as we get an error about enter not being a function\n+ // when trying to be used as a default below.\n+ defaults: {\n+ name: { value: '' },\n+ server: { value: '', type: 'server' },\n+ servicedomain: { value: '' },\n+ service: { value: '' },\n+ data: { value: '' }\n+ },\n+ inputs: 1,\n+ outputs: 1,\n+ icon: \"router-wireless.png\",\n+ align: 'right',\n+ paletteLabel: 'call service',\n+ label: function() { return this.name || `service: ${this.domain}:${this.service}`; }\n+ });\n+</script>\n+\n+\n<script type=\"text/x-red\" data-template-name=\"service-call\">\n<div class=\"form-row\">\n<label for=\"node-input-name\"><i class=\"fa fa-tag\"></i> Name</label>\n<p>Output is the server response from Home Assistant if needed</p>\n<p> NOTE: Service and Domain have to be set, either by node config or incoming message for a service call to be made</p>\n</script>\n-\n-<script type=\"text/javascript\">\n- // TODO: Look for autocomplete modules to allow a select drop down (with autocomplete)\n- // the options would be populated by the api query of services on the server node\n-\n- RED.nodes.registerType('service-call', {\n- category: 'home_assistant',\n- color: '#52C0F2',\n- // NOTE: 'domain' seems to be a nodered 'reserved' word as we get an error about enter not being a function\n- // when trying to be used as a default below.\n- defaults: {\n- name: { value: '' },\n- server: { value: '', type: 'server' },\n- servicedomain: { value: '' },\n- service: { value: '' },\n- data: { value: '' }\n- },\n- inputs: 1,\n- outputs: 1,\n- icon: \"arrow-out.png\",\n- label: function() { return this.name || 'call service'; }\n- });\n-</script>\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Added some placeholder icons, adjusted palette naming for better fit visually |
748,240 | 16.04.2017 19:42:06 | 14,400 | 99648a8ae932a648df220b584218aea3ff4e93f0 | Service Call node now has autocomplete for domains and services | [
{
"change_type": "MODIFY",
"old_path": "node-service-call/node-service-call.html",
"new_path": "node-service-call/node-service-call.html",
"diff": "<script type=\"text/javascript\">\n// TODO: Look for autocomplete modules to allow a select drop down (with autocomplete)\n// the options would be populated by the api query of services on the server node\n-\nRED.nodes.registerType('service-call', {\ncategory: 'home_assistant',\ncolor: '#52C0F2',\n+ inputs: 1,\n+ outputs: 0,\n+ icon: 'router-wireless.png',\n+ align: 'right',\n+ paletteLabel: 'call service',\n+ label: function() { return this.name || `svc: ${this.service_domain}:${this.service}`; },\n// NOTE: 'domain' seems to be a nodered 'reserved' word as we get an error about enter not being a function\n// when trying to be used as a default below.\ndefaults: {\nname: { value: '' },\nserver: { value: '', type: 'server' },\n- servicedomain: { value: '' },\n+ service_domain: { value: '' },\nservice: { value: '' },\ndata: { value: '' }\n},\n- inputs: 1,\n- outputs: 1,\n- icon: \"router-wireless.png\",\n- align: 'right',\n- paletteLabel: 'call service',\n- label: function() { return this.name || `service: ${this.domain}:${this.service}`; }\n+ oneditprepare: function () {\n+ const $domainField = $('#service_domain');\n+ const $serviceField = $('#service');\n+\n+ const $serviceDataDiv = $('#service-data-desc');\n+ const $serviceDescDiv = $('.service-description', $serviceDataDiv);\n+ const $serviceDataTableBody = $('tbody', $serviceDataDiv);\n+ const $unknownServiceDiv = $('.unknown-service', $serviceDataDiv);\n+ const $knownServiceDiv = $('.known-service', $serviceDataDiv);\n+\n+ function setServicesAndDomains(node) {\n+ return $.get('/homeassistant/services')\n+ .done(services => {\n+ node.allServices = JSON.parse(services);\n+ node.allDomains = node.allServices.map(s => s.domain);\n+ })\n+ .fail((err) => RED.notify(err.responseText, 'error'));\n+ }\n+\n+ function setServicesForDomainAutocomplete(node, services) {\n+ function updateServiceSelection(evt, serviceText) {\n+ // If a value selected\n+ if (serviceText) {\n+ node.selectedService = node.selectedDomain.services[serviceText];\n+ // If a known service\n+ if (node.selectedService) {\n+ const serviceDesc = node.selectedService.description;\n+ const fields = node.selectedService.fields;\n+\n+ let tableRows = Object.keys(fields).reduce((tRows, k) => {\n+ const fieldData = fields[k];\n+ if (!fieldData.description && !fieldData.example) { return; }\n+ tRows.push(`\n+ <tr>\n+ <td><code>${k}</code></td>\n+ <td>${fields[k].description || ''}</td>\n+ <td>${fields[k].example || ''}</td>\n+ </tr>`\n+ );\n+ return tRows;\n+ }, []);\n+\n+ tableRows = (tableRows.length > 0)\n+ ? tableRows.join('')\n+ : '';\n+\n+ // Add table and description for service and service fields\n+ $serviceDescDiv.html(serviceDesc);\n+ $serviceDataTableBody.html(tableRows);\n+ $unknownServiceDiv.hide();\n+ $knownServiceDiv.show();\n+ } else {\n+ // Hide service data fields and desc\n+ $unknownServiceDiv.show();\n+ $knownServiceDiv.hide();\n+ }\n+ } else {\n+ // Hide service data fields and desc\n+ $unknownServiceDiv.show();\n+ $knownServiceDiv.hide();\n+ }\n+ }\n+\n+\n+ $serviceField.autocomplete({\n+ source: Object.keys(services),\n+ create: (evt, ui) => updateServiceSelection(evt, $(evt.target).val()),\n+ change: (evt, ui) => updateServiceSelection(evt, $(evt.target).val()),\n+ select: (evt, ui) => updateServiceSelection(evt, $(evt.target).val()),\n+ focus: (evt, ui) => updateServiceSelection(evt, ui.item.label),\n+ minLength: 0\n+ })\n+ .focus(function() {\n+ $serviceField.autocomplete('search');\n+ });;\n+ }\n+\n+ function initDomainAutocomplete(node) {\n+\n+ function updateDomainSelection(evt, domainText) {\n+ const knownDomain = (node.allDomains.indexOf(domainText) > -1);\n+\n+ if (knownDomain) {\n+ node.selectedDomain = node.allServices.find(s => (s.domain === domainText));\n+ } else {\n+ node.selectedDomain = { services: {} };\n+ }\n+\n+ setServicesForDomainAutocomplete(node, node.selectedDomain.services);\n+ }\n+\n+ $domainField.autocomplete({\n+ source: node.allDomains,\n+ create: (evt, ui) => updateDomainSelection(evt, $(evt.target).val()),\n+ change: (evt, ui) => updateDomainSelection(evt, $(evt.target).val()),\n+ select: (evt, ui) => updateDomainSelection(evt, $(evt.target).val()),\n+ focus: (evt, ui) => updateDomainSelection(evt, ui.item.label),\n+ minLength: 0\n+ }).focus(function() {\n+ $domainField.autocomplete('search');\n+ });\n+ }\n+\n+ // ***********************************\n+ // ENTRY POINT\n+ // ***********************************\n+ const node = this;\n+ $domainField.val(node.service_domain);\n+ $serviceField.val(node.service);\n+\n+\n+ setServicesAndDomains(node).then(() => initDomainAutocomplete(node));\n+ },\n+ oneditsave: function() {\n+ this.service_domain = $(\"#service_domain\").val();\n+ this.service = $(\"#service\").val();\n+ }\n});\n</script>\n</div>\n<div class=\"form-row\">\n- <label for=\"node-input-servicedomain\"><i class=\"fa fa-dot-circle-o\"></i> Domain</label>\n- <input type=\"text\" id=\"node-input-servicedomain\" placeholder=\"light\"/>\n+ <label for=\"service_domain\"><i class=\"fa fa-cube\"></i> Domain</label>\n+ <input type=\"text\" id=\"service_domain\">\n+\n+ <!--<label for=\"node-input-servicedomain\"><i class=\"fa fa-dot-circle-o\"></i> Domain</label>\n+ <input type=\"text\" id=\"node-input-servicedomain\" placeholder=\"light\"/>-->\n</div>\n<div class=\"form-row\">\n- <label for=\"node-input-service\"><i class=\"fa fa-dot-circle-o\"></i> Service</label>\n- <input type=\"text\" id=\"node-input-service\" placeholder=\"toggle\"/>\n+ <label for=\"service\"><i class=\"fa fa-cube\"></i> Service</label>\n+ <input type=\"text\" id=\"service\">\n+\n+ <!--<label for=\"node-input-service\"><i class=\"fa fa-dot-circle-o\"></i> Service</label>\n+ <input type=\"text\" id=\"node-input-service\" placeholder=\"toggle\"/>-->\n</div>\n<div class=\"form-row\">\n<label for=\"node-input-data\"><i class=\"fa fa-dot-circle-o\"></i> Data</label>\n<input type=\"text\" id=\"node-input-data\" placeholder=\"{ entity_id: light.livingroom }\"/>\n</div>\n+\n+ <div id=\"service-data-desc\" class=\"form-row\">\n+ <h4>Service Data Fields</h4>\n+ <div class=\"unknown-service\">Unknown Service</div>\n+ <div class=\"known-service\">\n+ <p class='service-description'></p>\n+ <table id=\"service-data-table\" style=\"width: 100%;\" border=\"1\" cellpadding=\"10\">\n+ <thead>\n+ <tr>\n+ <th>Property</th>\n+ <th>Desc</th>\n+ <th>Example</th>\n+ </tr>\n+ </thead>\n+ <tbody>\n+ </tbody>\n+ </table>\n+ </div>\n+ </div>\n</script>\n<script type=\"text/x-red\" data-help-name=\"service-call\">\n<p>Call a Home Assistant service</p>\n<p>Set the node's domain, service and data defaults or allow the incoming message to define them, or both.</p>\n+\n<p>If the incoming message has a `payload` property with `domain`, `service` or `data`\nset it will override any defaults(if any) set within the node configuration.</p>\n<p>All other `msg.payload` properties are ignored</p>\n- <p>Output is the server response from Home Assistant if needed</p>\n<p> NOTE: Service and Domain have to be set, either by node config or incoming message for a service call to be made</p>\n</script>\n"
},
{
"change_type": "MODIFY",
"old_path": "node-service-call/node-service-call.js",
"new_path": "node-service-call/node-service-call.js",
"diff": "const debug = require('debug')('home-assistant:service-call');\nconst _int = {\n- getSettings: function(config) {\n- return {\n- domain: config.servicedomain,\n- service: config.service,\n- data: config.data\n- };\n+ getSettings: function(config, node) {\n+ node.service_domain = config.service_domain;\n+ node.service = config.service;\n+ node.data = config.data;\n+ return node;\n},\nflashStatus: function (node) {\nlet status = false;\n@@ -19,7 +18,10 @@ const _int = {\nsetTimeout(() => { clearInterval(flash); node.status({}); }, 1000);\n},\nonInput: function(msg, node) {\n- const { domain, service, data } = Object.assign({}, node.settings, msg.payload);\n+ const p = msg.payload;\n+ const domain = p.domain || node.service_domain;\n+ const service = p.service || node.service;\n+ const data = p.data ? Object.assign({}, node.data, p.data) : node.data;\nif (!domain || !service) {\nnode.warn('Domain or Service not set, skipping call service');\n@@ -27,8 +29,11 @@ const _int = {\n_int.flashStatus(node);\ndebug(`Calling Service: ${domain}:${service} -- ${JSON.stringify(data)}`);\nnode.server.api.callService(domain, service, data)\n- .then(res => node.send({ payload: { status: res.status, data: res.data } }))\n- .catch(err => node.error(err));\n+ .catch(err => {\n+ node.warn('Error calling service, home assistant api error');\n+ node.warn(err);\n+ node.error(err);\n+ });\n}\n}\n};\n@@ -39,7 +44,7 @@ module.exports = function(RED) {\nconst node = this;\nRED.nodes.createNode(this, config);\nnode.server = RED.nodes.getNode(config.server);\n- node.settings = _int.getSettings(config);\n+ _int.getSettings(config, node);\nnode.on('input', (msg) => _int.onInput(msg, node));\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Service Call node now has autocomplete for domains and services |
748,240 | 16.04.2017 22:14:38 | 14,400 | 9283f0eea2b128d739b1a36d250efdfce16bcdd7 | Readme and package.json updates | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "# Node Red Contrib Home Assistant\n-Various nodes to assist in setting up automation using node-red communicating with Home Assistant.\n+Various nodes to assist in setting up automation using [node-red](https://nodered.org/) communicating with [Home Assistant](https://home-assistant.io/).\n-## Gettings Started\n+## Project status\n+\n+Project is going through active development and as such will probably have a few 'growing pain' bugs as well as node type, input, output and functionality changes. At this stage backwards compatibility between versions is not a main concern and a new version may mean you'll have to recreate certain nodes.\n+\n+## Getting Started\nThis assumes you have [node-red](http://nodered.org/) already installed and working, if you need to install node-red see [here](http://nodered.org/docs/getting-started/installation)\n```shell\n$ cd cd ~/.node-red\n$ npm install node-red-contrib-home-assistant\n-$ Restart node-red\n+# then restart node-red\n```\n## Included Nodes\n+The installed nodes have more detailed information in the node-red info pane shown when the node is selected. Below is a quick summary\n+\n+### events: all\n+Listens for all types of events from home assistant\n+\n+### events: state\n+Listens for only `state_changed` events from home assistant\n+\n+### current state\n+Returns the last known state for any entity\n+\n+### call service\n+Sends a request to home assistant for any domain and service available ( light/turn_on, input_select/select_option, etc..)\n-### Incoming Events\n-This is probably where you want to get started. By default will send messages for each 'state_changed' event from home assistant. See the node's info panel for more details.\n+## Known issues\n-### Service Call\n-Calls the home assistant server's api for the node's defined domain and service, sending in any set data as the payload of the api call.\n+* If the connection to the home assistant server is lost the nodes may have to be redeployed ( by just introducing a small change and clicking 'deploy' in node-red) to start listening again\n+* Fields with autocomplete ( Domain, Service some Entity ID fields ) are in progress, they should work but need polish\n+* Currently only Server Sent Events are supported for listening to home assistant. Websockets will be implemented at some point in the future.\n+* Have not tested with more than one Home Assistant server configuration setup at one time within Node Red. It should work in theory, but...\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "{\n\"name\": \"node-red-contrib-home-assistant\",\n+ \"description\": \"node-red nodes to visually construct home automation with home assistant\",\n\"version\": \"0.1.1\",\n+ \"homepage\": \"https://github.com/AYapejian/node-red-contrib-home-assistant\",\n+ \"bugs\": {\n+ \"url\": \"https://github.com/AYapejian/node-red-contrib-home-assistant/issues\"\n+ },\n+ \"repository\": {\n+ \"type\": \"git\",\n+ \"url\": \"https://github.com/AYapejian/node-red-contrib-home-assistant\"\n+ },\n\"license\": \"MIT\",\n\"keywords\": [\n\"node-red\",\n- \"home-assistant\"\n+ \"home-assistant\",\n+ \"home automation\"\n],\n\"node-red\": {\n\"nodes\": {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Readme and package.json updates |
748,240 | 23.04.2017 08:25:14 | 14,400 | 8b374a95e3d8f8407d368f976428821306245d7a | Fixed bug with service call payload.data not being object merged correctly | [
{
"change_type": "MODIFY",
"old_path": "node-server-events/node-server-events.js",
"new_path": "node-server-events/node-server-events.js",
"diff": "@@ -27,6 +27,8 @@ module.exports = function(RED) {\nif (node.server.connected) { incomingEvents.setStatus(true, node); }\nconst eventsClient = node.server.events;\n+\n+\neventsClient.on('ha_events:all', (evt) => {\nnode.send({ event_type: evt.event_type, topic: evt.event_type, payload: evt});\n});\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-state-changed/node-server-state-changed.js",
"new_path": "node-server-state-changed/node-server-state-changed.js",
"diff": "@@ -68,6 +68,12 @@ const incomingEvents = {\n} else {\ndebug('Skipping event due to include or blacklist filter');\n}\n+ },\n+ handlers: {\n+ onStateChanged: (evt) => incomingEvents.onIncomingMessage(evt, incomingEvents.node),\n+ onClose: () => incomingEvents.setStatus(false, incomingEvents.node),\n+ onOpen: () => incomingEvents.setStatus(true, incomingEvents.node),\n+ onError: (err) => incomingEvents.setStatus(false, incomingEvents.node)\n}\n}\n@@ -81,21 +87,26 @@ module.exports = function(RED) {\nnode.server = RED.nodes.getNode(config.server);\nincomingEvents.setStatus(false, node);\n+ incomingEvents.node = node;\n// If the event source was setup start listening for events\nif (node.server) {\nif (node.server.connected) { incomingEvents.setStatus(true, node); }\nconst eventsClient = node.server.events;\n- eventsClient.on('ha_events:state_changed', (evt) => incomingEvents.onIncomingMessage(evt, node));\n- eventsClient.on('ha_events:close', () => incomingEvents.setStatus(false, node));\n- eventsClient.on('ha_events:open', () => incomingEvents.setStatus(true, node));\n- eventsClient.on('ha_events:error', (err) => {\n- incomingEvents.setStatus(false, node);\n- node.warn(err);\n+ eventsClient.on('ha_events:state_changed', incomingEvents.handlers.onStateChanged);\n+ eventsClient.on('ha_events:close', incomingEvents.handlers.onClose);\n+ eventsClient.on('ha_events:open', incomingEvents.handlers.onOpen);\n+ eventsClient.on('ha_events:error', incomingEvents.handlers.onError);\n+\n+ this.on('close', function(done) {\n+ eventsClient.removeListener('ha_events:state_changed', incomingEvents.handlers.onStateChanged);\n+ eventsClient.removeListener('ha_events:close', incomingEvents.handlers.onClose);\n+ eventsClient.removeListener('ha_events:open', incomingEvents.handlers.onOpen);\n+ eventsClient.removeListener('ha_events:error', incomingEvents.handlers.onError);\n+ done();\n});\n}\n}\n-\nRED.nodes.registerType('server-state-changed', EventsStateChange);\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "node-service-call/node-service-call.js",
"new_path": "node-service-call/node-service-call.js",
"diff": "'use strict';\nconst debug = require('debug')('home-assistant:service-call');\n+const isString = require('is-string');\nconst _int = {\ngetSettings: function(config, node) {\nnode.service_domain = config.service_domain;\nnode.service = config.service;\n- node.data = config.data;\n+ let data = config.data || {};\n+ if (isString(config.data)) {\n+ try { data = JSON.parse(config.data); }\n+ catch (e) { debug('JSON parse error'); }\n+ }\n+ node.data = data;\nreturn node;\n},\nflashStatus: function (node) {\n@@ -21,8 +27,15 @@ const _int = {\nconst p = msg.payload;\nconst domain = p.domain || node.service_domain;\nconst service = p.service || node.service;\n- const data = p.data ? Object.assign({}, node.data, p.data) : node.data;\n+ let data = p.data || {};\n+ debugger;\n+ if (isString(data)) {\n+ try { data = JSON.parse(p.data) }\n+ catch(e) { debug('JSON parse error'); }\n+ }\n+ data = Object.assign({}, node.data, data);\n+ debugger;\nif (!domain || !service) {\nnode.warn('Domain or Service not set, skipping call service');\n} else {\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "},\n\"dependencies\": {\n\"debug\": \"^2.6.3\",\n+ \"is-string\": \"^1.0.4\",\n\"node-home-assistant\": \"0.0.3\"\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "yarn.lock",
"new_path": "yarn.lock",
"diff": "@@ -26,6 +26,10 @@ [email protected]:\ndependencies:\ndebug \"^2.2.0\"\n+is-string@^1.0.4:\n+ version \"1.0.4\"\n+ resolved \"https://registry.yarnpkg.com/is-string/-/is-string-1.0.4.tgz#cc3a9b69857d621e963725a24caeec873b826e64\"\n+\[email protected]:\nversion \"0.7.2\"\nresolved \"https://registry.yarnpkg.com/ms/-/ms-0.7.2.tgz#ae25cf2512b3885a1d95d7f037868d8431124765\"\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Fixed bug with service call payload.data not being object merged correctly |
748,240 | 23.04.2017 10:03:12 | 14,400 | 7d20c71033cdd9ae754144349faeb06068ee0ddd | Cleanup event listeners, setMaxListeners to prevent warnings | [
{
"change_type": "ADD",
"old_path": null,
"new_path": ".vscode/settings.json",
"diff": "+{\n+ \"cSpell.enabled\": false\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "config-server/config-server.js",
"new_path": "config-server/config-server.js",
"diff": "@@ -19,6 +19,7 @@ module.exports = function(RED) {\nconst ha = node.homeAssistant = new HomeAssistant({ baseUrl: node.url, apiPass: node.pass });\nnode.api = ha.api;\nnode.events = ha.events;\n+ node.events.setMaxListeners(0);\n}\n// All known entities derived from current state\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-events/node-server-events.js",
"new_path": "node-server-events/node-server-events.js",
"diff": "@@ -9,6 +9,20 @@ const incomingEvents = {\nsetStatus: function setStatus(isConnected, node) {\nif (isConnected) { node.status({ fill: 'green', shape: 'ring', text: 'Connected' }); }\nelse { node.status({ fill: 'red', shape: 'ring', text: 'Disconnected' }) }\n+ },\n+ handlers: {\n+ onEvent: (evt) => {\n+ incomingEvents.node.send({ event_type: evt.event_type, topic: evt.event_type, payload: evt});\n+ },\n+ onClose: () => {\n+ incomingEvents.setStatus(false, incomingEvents.node)\n+ },\n+ onOpen: () => {\n+ incomingEvents.setStatus(true, incomingEvents.node)\n+ },\n+ onError: (err) => {\n+ incomingEvents.setStatus(false, incomingEvents.node)\n+ }\n}\n};\n@@ -17,6 +31,7 @@ module.exports = function(RED) {\nfunction EventsAll(config) {\nRED.nodes.createNode(this, config);\nconst node = this;\n+ incomingEvents.node = node;\nnode.settings = incomingEvents.getSettings(config);\nnode.server = RED.nodes.getNode(config.server);\n@@ -27,17 +42,17 @@ module.exports = function(RED) {\nif (node.server.connected) { incomingEvents.setStatus(true, node); }\nconst eventsClient = node.server.events;\n-\n-\n- eventsClient.on('ha_events:all', (evt) => {\n- node.send({ event_type: evt.event_type, topic: evt.event_type, payload: evt});\n- });\n-\n- eventsClient.on('ha_events:close', () => incomingEvents.setStatus(false, node));\n- eventsClient.on('ha_events:open', () => incomingEvents.setStatus(true, node));\n- eventsClient.on('ha_events:error', (err) => {\n- incomingEvents.setStatus(false, node);\n- node.warn(err);\n+ eventsClient.on('ha_events:all', incomingEvents.handlers.onEvent);\n+ eventsClient.on('ha_events:close', incomingEvents.handlers.onClose);\n+ eventsClient.on('ha_events:open', incomingEvents.handlers.onOpen);\n+ eventsClient.on('ha_events:error', incomingEvents.handlers.onError);\n+\n+ this.on('close', function(done) {\n+ eventsClient.removeListener('ha_events:all', incomingEvents.handlers.onEvent);\n+ eventsClient.removeListener('ha_events:close', incomingEvents.handlers.onClose);\n+ eventsClient.removeListener('ha_events:open', incomingEvents.handlers.onOpen);\n+ eventsClient.removeListener('ha_events:error', incomingEvents.handlers.onError);\n+ done();\n});\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-state-changed/node-server-state-changed.js",
"new_path": "node-server-state-changed/node-server-state-changed.js",
"diff": "@@ -70,10 +70,18 @@ const incomingEvents = {\n}\n},\nhandlers: {\n- onStateChanged: (evt) => incomingEvents.onIncomingMessage(evt, incomingEvents.node),\n- onClose: () => incomingEvents.setStatus(false, incomingEvents.node),\n- onOpen: () => incomingEvents.setStatus(true, incomingEvents.node),\n- onError: (err) => incomingEvents.setStatus(false, incomingEvents.node)\n+ onStateChanged: (evt) => {\n+ incomingEvents.onIncomingMessage(evt, incomingEvents.node)\n+ },\n+ onClose: () => {\n+ incomingEvents.setStatus(false, incomingEvents.node)\n+ },\n+ onOpen: () => {\n+ incomingEvents.setStatus(true, incomingEvents.node)\n+ },\n+ onError: (err) => {\n+ incomingEvents.setStatus(false, incomingEvents.node)\n+ }\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "node-service-call/node-service-call.js",
"new_path": "node-service-call/node-service-call.js",
"diff": "@@ -27,15 +27,14 @@ const _int = {\nconst p = msg.payload;\nconst domain = p.domain || node.service_domain;\nconst service = p.service || node.service;\n-\n- let data = p.data || {};\ndebugger;\n+ let data = p.data || {};\nif (isString(data)) {\ntry { data = JSON.parse(p.data) }\ncatch(e) { debug('JSON parse error'); }\n}\ndata = Object.assign({}, node.data, data);\n- debugger;\n+\nif (!domain || !service) {\nnode.warn('Domain or Service not set, skipping call service');\n} else {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Cleanup event listeners, setMaxListeners to prevent warnings |
748,240 | 24.04.2017 21:49:04 | 14,400 | 392487bd2f4415126a774252d7f6f3dc8cfeeaec | Fixed issue where node reference was being dropped and only last node shared between all handlers | [
{
"change_type": "MODIFY",
"old_path": "config-server/config-server.js",
"new_path": "config-server/config-server.js",
"diff": "@@ -19,7 +19,6 @@ module.exports = function(RED) {\nconst ha = node.homeAssistant = new HomeAssistant({ baseUrl: node.url, apiPass: node.pass });\nnode.api = ha.api;\nnode.events = ha.events;\n- node.events.setMaxListeners(0);\n}\n// All known entities derived from current state\n"
},
{
"change_type": "MODIFY",
"old_path": "node-current-state/node-current-state.html",
"new_path": "node-current-state/node-current-state.html",
"diff": "inputs: 1,\noutputs: 1,\nicon: \"arrow-top-right.png\",\n- paletteLabel: 'current state',\n+ // paletteLabel: 'current state',\nlabel: function() { return this.name || `current_state: ${this.entity_id}`; },\ndefaults: {\nname: { value: '' },\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-events/node-server-events.js",
"new_path": "node-server-events/node-server-events.js",
"diff": "'use strict';\nconst debug = require('debug')('home-assistant:server-events');\n-const incomingEvents = {\n+const _int = {\ngetSettings: function getSettings(config) {\nconst settings = {}\nreturn settings;\n@@ -10,18 +10,12 @@ const incomingEvents = {\nif (isConnected) { node.status({ fill: 'green', shape: 'ring', text: 'Connected' }); }\nelse { node.status({ fill: 'red', shape: 'ring', text: 'Disconnected' }) }\n},\n- handlers: {\n- onEvent: (evt) => {\n- incomingEvents.node.send({ event_type: evt.event_type, topic: evt.event_type, payload: evt});\n- },\n- onClose: () => {\n- incomingEvents.setStatus(false, incomingEvents.node)\n- },\n- onOpen: () => {\n- incomingEvents.setStatus(true, incomingEvents.node)\n- },\n- onError: (err) => {\n- incomingEvents.setStatus(false, incomingEvents.node)\n+ getHandlers: function(node) {\n+ return {\n+ onEvent: (evt) => node.send({ event_type: evt.event_type, topic: evt.event_type, payload: evt}),\n+ onClose: () => _int.setStatus(false, node),\n+ onOpen: () => _int.setStatus(true, node),\n+ onError: (err) => _int.setStatus(false, node)\n}\n}\n};\n@@ -31,27 +25,27 @@ module.exports = function(RED) {\nfunction EventsAll(config) {\nRED.nodes.createNode(this, config);\nconst node = this;\n- incomingEvents.node = node;\n- node.settings = incomingEvents.getSettings(config);\n+ _int.node = node;\n+ node.settings = _int.getSettings(config);\nnode.server = RED.nodes.getNode(config.server);\n- incomingEvents.setStatus(false, node);\n+ _int.setStatus(false, node);\n+ const handlers = _int.getHandlers(node);\n// If the event source was setup start listening for events\nif (node.server) {\n- if (node.server.connected) { incomingEvents.setStatus(true, node); }\nconst eventsClient = node.server.events;\n- eventsClient.on('ha_events:all', incomingEvents.handlers.onEvent);\n- eventsClient.on('ha_events:close', incomingEvents.handlers.onClose);\n- eventsClient.on('ha_events:open', incomingEvents.handlers.onOpen);\n- eventsClient.on('ha_events:error', incomingEvents.handlers.onError);\n+ eventsClient.on('ha_events:all', handlers.onEvent);\n+ eventsClient.on('ha_events:close', handlers.onClose);\n+ eventsClient.on('ha_events:open', handlers.onOpen);\n+ eventsClient.on('ha_events:error', handlers.onError);\nthis.on('close', function(done) {\n- eventsClient.removeListener('ha_events:all', incomingEvents.handlers.onEvent);\n- eventsClient.removeListener('ha_events:close', incomingEvents.handlers.onClose);\n- eventsClient.removeListener('ha_events:open', incomingEvents.handlers.onOpen);\n- eventsClient.removeListener('ha_events:error', incomingEvents.handlers.onError);\n+ eventsClient.removeListener('ha_events:all', handlers.onEvent);\n+ eventsClient.removeListener('ha_events:close', handlers.onClose);\n+ eventsClient.removeListener('ha_events:open', handlers.onOpen);\n+ eventsClient.removeListener('ha_events:error', handlers.onError);\ndone();\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-state-changed/node-server-state-changed.js",
"new_path": "node-server-state-changed/node-server-state-changed.js",
"diff": "'use strict';\nconst debug = require('debug')('home-assistant:server-state-changed');\n-const incomingEvents = {\n+const _int = {\ngetSettings: function getSettings(config) {\nconst settings = {\nentityIdFilter: config.entityidfilter ? config.entityidfilter.split(',').map(f => f.trim()) : null,\n@@ -18,14 +18,11 @@ const incomingEvents = {\nshouldSkipNoChange: function shouldSkipNoChange(e, node) {\nif (!e.event || !e.event.old_state || !e.event.new_state) { return false; }\nconst shouldSkip = (e.event.old_state.state === e.event.new_state.state);\n-\n- if (shouldSkip) { debug('Skipping event, state unchanged new vs. old'); }\nreturn shouldSkip;\n},\nshouldSkipIfState: function shouldSkipIfState(e, skipIfState) {\nif (!skipIfState) { return false; }\nconst shouldSkip = (skipIfState === e.event.new_state.state);\n- if (shouldSkip) { debug('Skipping event, incoming event state === skipIfState setting'); }\nreturn shouldSkip;\n},\nshouldIncludeEvent: function shouldIncludeEvent(entityId, { entityIdFilter, entityIdBlacklist }) {\n@@ -53,8 +50,8 @@ const incomingEvents = {\n},\n/* eslint-disable consistent-return */\nonIncomingMessage: function onIncomingMessage(evt, node) {\n- if (incomingEvents.shouldSkipNoChange(evt, node)) { return null; }\n- if (incomingEvents.shouldSkipIfState(evt, node.settings.skipIfState)) { return null; }\n+ if (_int.shouldSkipNoChange(evt, node)) { return null; }\n+ if (_int.shouldSkipIfState(evt, node.settings.skipIfState)) { return null; }\nconst { entity_id, event } = evt;\nconst msg = {\n@@ -63,55 +60,44 @@ const incomingEvents = {\nevent: event\n};\n- if (incomingEvents.shouldIncludeEvent(entity_id, node.settings)) {\n+ if (_int.shouldIncludeEvent(entity_id, node.settings)) {\nnode.send(msg);\n- } else {\n- debug('Skipping event due to include or blacklist filter');\n}\n},\n- handlers: {\n- onStateChanged: (evt) => {\n- incomingEvents.onIncomingMessage(evt, incomingEvents.node)\n- },\n- onClose: () => {\n- incomingEvents.setStatus(false, incomingEvents.node)\n- },\n- onOpen: () => {\n- incomingEvents.setStatus(true, incomingEvents.node)\n- },\n- onError: (err) => {\n- incomingEvents.setStatus(false, incomingEvents.node)\n- }\n+ getHandlers: function(node) {\n+ return {\n+ onStateChanged: (evt) => _int.onIncomingMessage(evt, node),\n+ onClose: () => _int.setStatus(false, node),\n+ onOpen: () => _int.setStatus(true, node),\n+ onError: (err) => _int.setStatus(false, node)\n+ };\n}\n}\n-\n-\nmodule.exports = function(RED) {\nfunction EventsStateChange(config) {\nRED.nodes.createNode(this, config);\nconst node = this;\n- node.settings = incomingEvents.getSettings(config);\n+ node.settings = _int.getSettings(config);\nnode.server = RED.nodes.getNode(config.server);\n- incomingEvents.setStatus(false, node);\n- incomingEvents.node = node;\n+ _int.setStatus(false, node);\n+ const handlers = _int.getHandlers(node);\n// If the event source was setup start listening for events\nif (node.server) {\n- if (node.server.connected) { incomingEvents.setStatus(true, node); }\nconst eventsClient = node.server.events;\n- eventsClient.on('ha_events:state_changed', incomingEvents.handlers.onStateChanged);\n- eventsClient.on('ha_events:close', incomingEvents.handlers.onClose);\n- eventsClient.on('ha_events:open', incomingEvents.handlers.onOpen);\n- eventsClient.on('ha_events:error', incomingEvents.handlers.onError);\n+ eventsClient.on('ha_events:state_changed', handlers.onStateChanged);\n+ eventsClient.on('ha_events:close', handlers.onClose);\n+ eventsClient.on('ha_events:open', handlers.onOpen);\n+ eventsClient.on('ha_events:error', handlers.onError);\nthis.on('close', function(done) {\n- eventsClient.removeListener('ha_events:state_changed', incomingEvents.handlers.onStateChanged);\n- eventsClient.removeListener('ha_events:close', incomingEvents.handlers.onClose);\n- eventsClient.removeListener('ha_events:open', incomingEvents.handlers.onOpen);\n- eventsClient.removeListener('ha_events:error', incomingEvents.handlers.onError);\n+ eventsClient.removeListener('ha_events:state_changed', handlers.onStateChanged);\n+ eventsClient.removeListener('ha_events:close', handlers.onClose);\n+ eventsClient.removeListener('ha_events:open', handlers.onOpen);\n+ eventsClient.removeListener('ha_events:error', handlers.onError);\ndone();\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "node-service-call/node-service-call.js",
"new_path": "node-service-call/node-service-call.js",
"diff": "@@ -9,7 +9,10 @@ const _int = {\nlet data = config.data || {};\nif (isString(config.data)) {\ntry { data = JSON.parse(config.data); }\n- catch (e) { debug('JSON parse error'); }\n+ catch (e) {\n+ debug('JSON parse error');\n+ debug(require('utils').inspect(config.data));\n+ }\n}\nnode.data = data;\nreturn node;\n@@ -27,11 +30,15 @@ const _int = {\nconst p = msg.payload;\nconst domain = p.domain || node.service_domain;\nconst service = p.service || node.service;\n- debugger;\n+\nlet data = p.data || {};\n+\nif (isString(data)) {\ntry { data = JSON.parse(p.data) }\n- catch(e) { debug('JSON parse error'); }\n+ catch (e) {\n+ debug('JSON parse error');\n+ debug(require('utils').inspect(config.data));\n+ }\n}\ndata = Object.assign({}, node.data, data);\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"node-red\": {\n\"nodes\": {\n\"server\": \"config-server/config-server.js\",\n+ \"current-state\": \"node-current-state/node-current-state.js\",\n\"server-events\": \"node-server-events/node-server-events.js\",\n\"server-state-changed\": \"node-server-state-changed/node-server-state-changed.js\",\n- \"service-call\": \"node-service-call/node-service-call.js\",\n- \"current-state\": \"node-current-state/node-current-state.js\"\n+ \"service-call\": \"node-service-call/node-service-call.js\"\n}\n},\n\"dependencies\": {\n\"debug\": \"^2.6.3\",\n\"is-string\": \"^1.0.4\",\n\"node-home-assistant\": \"0.0.3\"\n+ },\n+ \"devDependencies\": {\n+ \"inspect-process\": \"^0.4.2\"\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "yarn.lock",
"new_path": "yarn.lock",
"diff": "# yarn lockfile v1\n+adm-zip@^0.4.7:\n+ version \"0.4.7\"\n+ resolved \"https://registry.yarnpkg.com/adm-zip/-/adm-zip-0.4.7.tgz#8606c2cbf1c426ce8c8ec00174447fd49b6eafc1\"\n+\n+ansi-regex@^2.0.0:\n+ version \"2.1.1\"\n+ resolved \"https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df\"\n+\n+aproba@^1.0.3:\n+ version \"1.1.1\"\n+ resolved \"https://registry.yarnpkg.com/aproba/-/aproba-1.1.1.tgz#95d3600f07710aa0e9298c726ad5ecf2eacbabab\"\n+\n+are-we-there-yet@~1.1.2:\n+ version \"1.1.4\"\n+ resolved \"https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-1.1.4.tgz#bb5dca382bb94f05e15194373d16fd3ba1ca110d\"\n+ dependencies:\n+ delegates \"^1.0.0\"\n+ readable-stream \"^2.0.6\"\n+\n+async@^1.5.2:\n+ version \"1.5.2\"\n+ resolved \"https://registry.yarnpkg.com/async/-/async-1.5.2.tgz#ec6a61ae56480c0c3cb241c95618e20892f9672a\"\n+\naxios@^0.15.3:\nversion \"0.15.3\"\nresolved \"https://registry.yarnpkg.com/axios/-/axios-0.15.3.tgz#2c9d638b2e191a08ea1d6cc988eadd6ba5bdc053\"\ndependencies:\nfollow-redirects \"1.0.0\"\n+balanced-match@^0.4.1:\n+ version \"0.4.2\"\n+ resolved \"https://registry.yarnpkg.com/balanced-match/-/balanced-match-0.4.2.tgz#cb3f3e3c732dc0f01ee70b403f302e61d7709838\"\n+\n+brace-expansion@^1.0.0:\n+ version \"1.1.7\"\n+ resolved \"https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.7.tgz#3effc3c50e000531fb720eaff80f0ae8ef23cf59\"\n+ dependencies:\n+ balanced-match \"^0.4.1\"\n+ concat-map \"0.0.1\"\n+\n+buffer-shims@~1.0.0:\n+ version \"1.0.0\"\n+ resolved \"https://registry.yarnpkg.com/buffer-shims/-/buffer-shims-1.0.0.tgz#9978ce317388c649ad8793028c3477ef044a8b51\"\n+\n+builtin-modules@^1.0.0:\n+ version \"1.1.1\"\n+ resolved \"https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-1.1.1.tgz#270f076c5a72c02f5b65a47df94c5fe3a278892f\"\n+\n+camelcase@^3.0.0:\n+ version \"3.0.0\"\n+ resolved \"https://registry.yarnpkg.com/camelcase/-/camelcase-3.0.0.tgz#32fc4b9fcdaf845fcdf7e73bb97cac2261f0ab0a\"\n+\n+chromedriver@^2.26.1:\n+ version \"2.29.0\"\n+ resolved \"https://registry.yarnpkg.com/chromedriver/-/chromedriver-2.29.0.tgz#e3fd8b3c08dce2562b80ef1b0b846597659d0cc3\"\n+ dependencies:\n+ adm-zip \"^0.4.7\"\n+ kew \"^0.7.0\"\n+ mkdirp \"^0.5.1\"\n+ rimraf \"^2.5.4\"\n+\n+cliui@^3.2.0:\n+ version \"3.2.0\"\n+ resolved \"https://registry.yarnpkg.com/cliui/-/cliui-3.2.0.tgz#120601537a916d29940f934da3b48d585a39213d\"\n+ dependencies:\n+ string-width \"^1.0.1\"\n+ strip-ansi \"^3.0.1\"\n+ wrap-ansi \"^2.0.0\"\n+\n+code-point-at@^1.0.0:\n+ version \"1.1.0\"\n+ resolved \"https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77\"\n+\[email protected]:\n+ version \"0.0.1\"\n+ resolved \"https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b\"\n+\n+console-control-strings@^1.0.0, console-control-strings@~1.1.0:\n+ version \"1.1.0\"\n+ resolved \"https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e\"\n+\n+core-util-is@~1.0.0:\n+ version \"1.0.2\"\n+ resolved \"https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7\"\n+\ndebug@^2.2.0, debug@^2.6.3:\nversion \"2.6.3\"\nresolved \"https://registry.yarnpkg.com/debug/-/debug-2.6.3.tgz#0f7eb8c30965ec08c72accfa0130c8b79984141d\"\ndependencies:\nms \"0.7.2\"\n+decamelize@^1.1.1:\n+ version \"1.2.0\"\n+ resolved \"https://registry.yarnpkg.com/decamelize/-/decamelize-1.2.0.tgz#f6534d15148269b20352e7bee26f501f9a191290\"\n+\n+delegates@^1.0.0:\n+ version \"1.0.0\"\n+ resolved \"https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a\"\n+\n+error-ex@^1.2.0:\n+ version \"1.3.1\"\n+ resolved \"https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.1.tgz#f855a86ce61adc4e8621c3cda21e7a7612c3a8dc\"\n+ dependencies:\n+ is-arrayish \"^0.2.1\"\n+\neventsource@^0.2.2:\nversion \"0.2.2\"\nresolved \"https://registry.yarnpkg.com/eventsource/-/eventsource-0.2.2.tgz#8ac0576cbd16ee83478b3faaf27bdc7b7c8fcca9\"\ndependencies:\noriginal \"^1.0.0\"\n+exit-hook@^1.1.1:\n+ version \"1.1.1\"\n+ resolved \"https://registry.yarnpkg.com/exit-hook/-/exit-hook-1.1.1.tgz#f05ca233b48c05d54fff07765df8507e95c02ff8\"\n+\n+find-up@^1.0.0:\n+ version \"1.1.2\"\n+ resolved \"https://registry.yarnpkg.com/find-up/-/find-up-1.1.2.tgz#6b2e9822b1a2ce0a60ab64d610eccad53cb24d0f\"\n+ dependencies:\n+ path-exists \"^2.0.0\"\n+ pinkie-promise \"^2.0.0\"\n+\[email protected]:\nversion \"1.0.0\"\nresolved \"https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.0.0.tgz#8e34298cbd2e176f254effec75a1c78cc849fd37\"\ndependencies:\ndebug \"^2.2.0\"\n+fs.realpath@^1.0.0:\n+ version \"1.0.0\"\n+ resolved \"https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f\"\n+\n+gauge@~2.7.1:\n+ version \"2.7.4\"\n+ resolved \"https://registry.yarnpkg.com/gauge/-/gauge-2.7.4.tgz#2c03405c7538c39d7eb37b317022e325fb018bf7\"\n+ dependencies:\n+ aproba \"^1.0.3\"\n+ console-control-strings \"^1.0.0\"\n+ has-unicode \"^2.0.0\"\n+ object-assign \"^4.1.0\"\n+ signal-exit \"^3.0.0\"\n+ string-width \"^1.0.1\"\n+ strip-ansi \"^3.0.1\"\n+ wide-align \"^1.1.0\"\n+\n+get-caller-file@^1.0.1:\n+ version \"1.0.2\"\n+ resolved \"https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-1.0.2.tgz#f702e63127e7e231c160a80c1554acb70d5047e5\"\n+\n+glob@^7.0.5:\n+ version \"7.1.1\"\n+ resolved \"https://registry.yarnpkg.com/glob/-/glob-7.1.1.tgz#805211df04faaf1c63a3600306cdf5ade50b2ec8\"\n+ dependencies:\n+ fs.realpath \"^1.0.0\"\n+ inflight \"^1.0.4\"\n+ inherits \"2\"\n+ minimatch \"^3.0.2\"\n+ once \"^1.3.0\"\n+ path-is-absolute \"^1.0.0\"\n+\n+graceful-fs@^4.1.2:\n+ version \"4.1.11\"\n+ resolved \"https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.11.tgz#0e8bdfe4d1ddb8854d64e04ea7c00e2a026e5658\"\n+\n+has-unicode@^2.0.0:\n+ version \"2.0.1\"\n+ resolved \"https://registry.yarnpkg.com/has-unicode/-/has-unicode-2.0.1.tgz#e0e6fe6a28cf51138855e086d1691e771de2a8b9\"\n+\n+hosted-git-info@^2.1.4:\n+ version \"2.4.2\"\n+ resolved \"https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.4.2.tgz#0076b9f46a270506ddbaaea56496897460612a67\"\n+\n+inflight@^1.0.4:\n+ version \"1.0.6\"\n+ resolved \"https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9\"\n+ dependencies:\n+ once \"^1.3.0\"\n+ wrappy \"1\"\n+\n+inherits@2, inherits@~2.0.1:\n+ version \"2.0.3\"\n+ resolved \"https://registry.yarnpkg.com/inherits/-/inherits-2.0.3.tgz#633c2c83e3da42a502f52466022480f4208261de\"\n+\n+inspect-process@^0.4.2:\n+ version \"0.4.2\"\n+ resolved \"https://registry.yarnpkg.com/inspect-process/-/inspect-process-0.4.2.tgz#26826a77137ae58f14440513f14d14667978d85b\"\n+ dependencies:\n+ chromedriver \"^2.26.1\"\n+ exit-hook \"^1.1.1\"\n+ lodash \"^4.17.2\"\n+ nodeflags \"^0.0.1\"\n+ npmlog \"^4.0.2\"\n+ portfinder \"^1.0.10\"\n+ selenium-webdriver \"^3.0.1\"\n+ which \"^1.2.12\"\n+ yargs \"^6.5.0\"\n+\n+invert-kv@^1.0.0:\n+ version \"1.0.0\"\n+ resolved \"https://registry.yarnpkg.com/invert-kv/-/invert-kv-1.0.0.tgz#104a8e4aaca6d3d8cd157a8ef8bfab2d7a3ffdb6\"\n+\n+is-arrayish@^0.2.1:\n+ version \"0.2.1\"\n+ resolved \"https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d\"\n+\n+is-builtin-module@^1.0.0:\n+ version \"1.0.0\"\n+ resolved \"https://registry.yarnpkg.com/is-builtin-module/-/is-builtin-module-1.0.0.tgz#540572d34f7ac3119f8f76c30cbc1b1e037affbe\"\n+ dependencies:\n+ builtin-modules \"^1.0.0\"\n+\n+is-fullwidth-code-point@^1.0.0:\n+ version \"1.0.0\"\n+ resolved \"https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb\"\n+ dependencies:\n+ number-is-nan \"^1.0.0\"\n+\nis-string@^1.0.4:\nversion \"1.0.4\"\nresolved \"https://registry.yarnpkg.com/is-string/-/is-string-1.0.4.tgz#cc3a9b69857d621e963725a24caeec873b826e64\"\n+is-utf8@^0.2.0:\n+ version \"0.2.1\"\n+ resolved \"https://registry.yarnpkg.com/is-utf8/-/is-utf8-0.2.1.tgz#4b0da1442104d1b336340e80797e865cf39f7d72\"\n+\n+isarray@~1.0.0:\n+ version \"1.0.0\"\n+ resolved \"https://registry.yarnpkg.com/isarray/-/isarray-1.0.0.tgz#bb935d48582cba168c06834957a54a3e07124f11\"\n+\n+isexe@^2.0.0:\n+ version \"2.0.0\"\n+ resolved \"https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10\"\n+\n+kew@^0.7.0:\n+ version \"0.7.0\"\n+ resolved \"https://registry.yarnpkg.com/kew/-/kew-0.7.0.tgz#79d93d2d33363d6fdd2970b335d9141ad591d79b\"\n+\n+lcid@^1.0.0:\n+ version \"1.0.0\"\n+ resolved \"https://registry.yarnpkg.com/lcid/-/lcid-1.0.0.tgz#308accafa0bc483a3867b4b6f2b9506251d1b835\"\n+ dependencies:\n+ invert-kv \"^1.0.0\"\n+\n+load-json-file@^1.0.0:\n+ version \"1.1.0\"\n+ resolved \"https://registry.yarnpkg.com/load-json-file/-/load-json-file-1.1.0.tgz#956905708d58b4bab4c2261b04f59f31c99374c0\"\n+ dependencies:\n+ graceful-fs \"^4.1.2\"\n+ parse-json \"^2.2.0\"\n+ pify \"^2.0.0\"\n+ pinkie-promise \"^2.0.0\"\n+ strip-bom \"^2.0.0\"\n+\n+lodash@^4.0.0, lodash@^4.17.2, lodash@^4.17.3:\n+ version \"4.17.4\"\n+ resolved \"https://registry.yarnpkg.com/lodash/-/lodash-4.17.4.tgz#78203a4d1c328ae1d86dca6460e369b57f4055ae\"\n+\n+minimatch@^3.0.2:\n+ version \"3.0.3\"\n+ resolved \"https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.3.tgz#2a4e4090b96b2db06a9d7df01055a62a77c9b774\"\n+ dependencies:\n+ brace-expansion \"^1.0.0\"\n+\[email protected]:\n+ version \"0.0.8\"\n+ resolved \"https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d\"\n+\[email protected], mkdirp@^0.5.1:\n+ version \"0.5.1\"\n+ resolved \"https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903\"\n+ dependencies:\n+ minimist \"0.0.8\"\n+\[email protected]:\nversion \"0.7.2\"\nresolved \"https://registry.yarnpkg.com/ms/-/ms-0.7.2.tgz#ae25cf2512b3885a1d95d7f037868d8431124765\"\n@@ -42,23 +287,324 @@ [email protected]:\ndebug \"^2.6.3\"\neventsource \"^0.2.2\"\n+nodeflags@^0.0.1:\n+ version \"0.0.1\"\n+ resolved \"https://registry.yarnpkg.com/nodeflags/-/nodeflags-0.0.1.tgz#0e28cedaea9ebe265e97f92b79fb30898245fa17\"\n+ dependencies:\n+ lodash \"^4.17.3\"\n+ semver \"^5.3.0\"\n+ v8flags \"^2.0.11\"\n+\n+normalize-package-data@^2.3.2:\n+ version \"2.3.8\"\n+ resolved \"https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.3.8.tgz#d819eda2a9dedbd1ffa563ea4071d936782295bb\"\n+ dependencies:\n+ hosted-git-info \"^2.1.4\"\n+ is-builtin-module \"^1.0.0\"\n+ semver \"2 || 3 || 4 || 5\"\n+ validate-npm-package-license \"^3.0.1\"\n+\n+npmlog@^4.0.2:\n+ version \"4.0.2\"\n+ resolved \"https://registry.yarnpkg.com/npmlog/-/npmlog-4.0.2.tgz#d03950e0e78ce1527ba26d2a7592e9348ac3e75f\"\n+ dependencies:\n+ are-we-there-yet \"~1.1.2\"\n+ console-control-strings \"~1.1.0\"\n+ gauge \"~2.7.1\"\n+ set-blocking \"~2.0.0\"\n+\n+number-is-nan@^1.0.0:\n+ version \"1.0.1\"\n+ resolved \"https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d\"\n+\n+object-assign@^4.1.0:\n+ version \"4.1.1\"\n+ resolved \"https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863\"\n+\n+once@^1.3.0:\n+ version \"1.4.0\"\n+ resolved \"https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1\"\n+ dependencies:\n+ wrappy \"1\"\n+\noriginal@^1.0.0:\nversion \"1.0.0\"\nresolved \"https://registry.yarnpkg.com/original/-/original-1.0.0.tgz#9147f93fa1696d04be61e01bd50baeaca656bd3b\"\ndependencies:\nurl-parse \"1.0.x\"\n+os-locale@^1.4.0:\n+ version \"1.4.0\"\n+ resolved \"https://registry.yarnpkg.com/os-locale/-/os-locale-1.4.0.tgz#20f9f17ae29ed345e8bde583b13d2009803c14d9\"\n+ dependencies:\n+ lcid \"^1.0.0\"\n+\n+os-tmpdir@~1.0.1:\n+ version \"1.0.2\"\n+ resolved \"https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274\"\n+\n+parse-json@^2.2.0:\n+ version \"2.2.0\"\n+ resolved \"https://registry.yarnpkg.com/parse-json/-/parse-json-2.2.0.tgz#f480f40434ef80741f8469099f8dea18f55a4dc9\"\n+ dependencies:\n+ error-ex \"^1.2.0\"\n+\n+path-exists@^2.0.0:\n+ version \"2.1.0\"\n+ resolved \"https://registry.yarnpkg.com/path-exists/-/path-exists-2.1.0.tgz#0feb6c64f0fc518d9a754dd5efb62c7022761f4b\"\n+ dependencies:\n+ pinkie-promise \"^2.0.0\"\n+\n+path-is-absolute@^1.0.0:\n+ version \"1.0.1\"\n+ resolved \"https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f\"\n+\n+path-type@^1.0.0:\n+ version \"1.1.0\"\n+ resolved \"https://registry.yarnpkg.com/path-type/-/path-type-1.1.0.tgz#59c44f7ee491da704da415da5a4070ba4f8fe441\"\n+ dependencies:\n+ graceful-fs \"^4.1.2\"\n+ pify \"^2.0.0\"\n+ pinkie-promise \"^2.0.0\"\n+\n+pify@^2.0.0:\n+ version \"2.3.0\"\n+ resolved \"https://registry.yarnpkg.com/pify/-/pify-2.3.0.tgz#ed141a6ac043a849ea588498e7dca8b15330e90c\"\n+\n+pinkie-promise@^2.0.0:\n+ version \"2.0.1\"\n+ resolved \"https://registry.yarnpkg.com/pinkie-promise/-/pinkie-promise-2.0.1.tgz#2135d6dfa7a358c069ac9b178776288228450ffa\"\n+ dependencies:\n+ pinkie \"^2.0.0\"\n+\n+pinkie@^2.0.0:\n+ version \"2.0.4\"\n+ resolved \"https://registry.yarnpkg.com/pinkie/-/pinkie-2.0.4.tgz#72556b80cfa0d48a974e80e77248e80ed4f7f870\"\n+\n+portfinder@^1.0.10:\n+ version \"1.0.13\"\n+ resolved \"https://registry.yarnpkg.com/portfinder/-/portfinder-1.0.13.tgz#bb32ecd87c27104ae6ee44b5a3ccbf0ebb1aede9\"\n+ dependencies:\n+ async \"^1.5.2\"\n+ debug \"^2.2.0\"\n+ mkdirp \"0.5.x\"\n+\n+process-nextick-args@~1.0.6:\n+ version \"1.0.7\"\n+ resolved \"https://registry.yarnpkg.com/process-nextick-args/-/process-nextick-args-1.0.7.tgz#150e20b756590ad3f91093f25a4f2ad8bff30ba3\"\n+\[email protected]:\nversion \"0.0.4\"\nresolved \"https://registry.yarnpkg.com/querystringify/-/querystringify-0.0.4.tgz#0cf7f84f9463ff0ae51c4c4b142d95be37724d9c\"\n+read-pkg-up@^1.0.1:\n+ version \"1.0.1\"\n+ resolved \"https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-1.0.1.tgz#9d63c13276c065918d57f002a57f40a1b643fb02\"\n+ dependencies:\n+ find-up \"^1.0.0\"\n+ read-pkg \"^1.0.0\"\n+\n+read-pkg@^1.0.0:\n+ version \"1.1.0\"\n+ resolved \"https://registry.yarnpkg.com/read-pkg/-/read-pkg-1.1.0.tgz#f5ffaa5ecd29cb31c0474bca7d756b6bb29e3f28\"\n+ dependencies:\n+ load-json-file \"^1.0.0\"\n+ normalize-package-data \"^2.3.2\"\n+ path-type \"^1.0.0\"\n+\n+readable-stream@^2.0.6:\n+ version \"2.2.9\"\n+ resolved \"https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.2.9.tgz#cf78ec6f4a6d1eb43d26488cac97f042e74b7fc8\"\n+ dependencies:\n+ buffer-shims \"~1.0.0\"\n+ core-util-is \"~1.0.0\"\n+ inherits \"~2.0.1\"\n+ isarray \"~1.0.0\"\n+ process-nextick-args \"~1.0.6\"\n+ string_decoder \"~1.0.0\"\n+ util-deprecate \"~1.0.1\"\n+\n+require-directory@^2.1.1:\n+ version \"2.1.1\"\n+ resolved \"https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42\"\n+\n+require-main-filename@^1.0.1:\n+ version \"1.0.1\"\n+ resolved \"https://registry.yarnpkg.com/require-main-filename/-/require-main-filename-1.0.1.tgz#97f717b69d48784f5f526a6c5aa8ffdda055a4d1\"\n+\[email protected]:\nversion \"1.0.0\"\nresolved \"https://registry.yarnpkg.com/requires-port/-/requires-port-1.0.0.tgz#925d2601d39ac485e091cf0da5c6e694dc3dcaff\"\n+rimraf@^2.5.4:\n+ version \"2.6.1\"\n+ resolved \"https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.1.tgz#c2338ec643df7a1b7fe5c54fa86f57428a55f33d\"\n+ dependencies:\n+ glob \"^7.0.5\"\n+\n+sax@>=0.6.0:\n+ version \"1.2.2\"\n+ resolved \"https://registry.yarnpkg.com/sax/-/sax-1.2.2.tgz#fd8631a23bc7826bef5d871bdb87378c95647828\"\n+\n+selenium-webdriver@^3.0.1:\n+ version \"3.4.0\"\n+ resolved \"https://registry.yarnpkg.com/selenium-webdriver/-/selenium-webdriver-3.4.0.tgz#151f7445294da6a66c49cc300747a2a17e53c52a\"\n+ dependencies:\n+ adm-zip \"^0.4.7\"\n+ rimraf \"^2.5.4\"\n+ tmp \"0.0.30\"\n+ xml2js \"^0.4.17\"\n+\n+\"semver@2 || 3 || 4 || 5\", semver@^5.3.0:\n+ version \"5.3.0\"\n+ resolved \"https://registry.yarnpkg.com/semver/-/semver-5.3.0.tgz#9b2ce5d3de02d17c6012ad326aa6b4d0cf54f94f\"\n+\n+set-blocking@^2.0.0, set-blocking@~2.0.0:\n+ version \"2.0.0\"\n+ resolved \"https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7\"\n+\n+signal-exit@^3.0.0:\n+ version \"3.0.2\"\n+ resolved \"https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.2.tgz#b5fdc08f1287ea1178628e415e25132b73646c6d\"\n+\n+spdx-correct@~1.0.0:\n+ version \"1.0.2\"\n+ resolved \"https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-1.0.2.tgz#4b3073d933ff51f3912f03ac5519498a4150db40\"\n+ dependencies:\n+ spdx-license-ids \"^1.0.2\"\n+\n+spdx-expression-parse@~1.0.0:\n+ version \"1.0.4\"\n+ resolved \"https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-1.0.4.tgz#9bdf2f20e1f40ed447fbe273266191fced51626c\"\n+\n+spdx-license-ids@^1.0.2:\n+ version \"1.2.2\"\n+ resolved \"https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-1.2.2.tgz#c9df7a3424594ade6bd11900d596696dc06bac57\"\n+\n+string-width@^1.0.1, string-width@^1.0.2:\n+ version \"1.0.2\"\n+ resolved \"https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3\"\n+ dependencies:\n+ code-point-at \"^1.0.0\"\n+ is-fullwidth-code-point \"^1.0.0\"\n+ strip-ansi \"^3.0.0\"\n+\n+string_decoder@~1.0.0:\n+ version \"1.0.0\"\n+ resolved \"https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.0.0.tgz#f06f41157b664d86069f84bdbdc9b0d8ab281667\"\n+ dependencies:\n+ buffer-shims \"~1.0.0\"\n+\n+strip-ansi@^3.0.0, strip-ansi@^3.0.1:\n+ version \"3.0.1\"\n+ resolved \"https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf\"\n+ dependencies:\n+ ansi-regex \"^2.0.0\"\n+\n+strip-bom@^2.0.0:\n+ version \"2.0.0\"\n+ resolved \"https://registry.yarnpkg.com/strip-bom/-/strip-bom-2.0.0.tgz#6219a85616520491f35788bdbf1447a99c7e6b0e\"\n+ dependencies:\n+ is-utf8 \"^0.2.0\"\n+\[email protected]:\n+ version \"0.0.30\"\n+ resolved \"https://registry.yarnpkg.com/tmp/-/tmp-0.0.30.tgz#72419d4a8be7d6ce75148fd8b324e593a711c2ed\"\n+ dependencies:\n+ os-tmpdir \"~1.0.1\"\n+\[email protected]:\nversion \"1.0.5\"\nresolved \"https://registry.yarnpkg.com/url-parse/-/url-parse-1.0.5.tgz#0854860422afdcfefeb6c965c662d4800169927b\"\ndependencies:\nquerystringify \"0.0.x\"\nrequires-port \"1.0.x\"\n+\n+user-home@^1.1.1:\n+ version \"1.1.1\"\n+ resolved \"https://registry.yarnpkg.com/user-home/-/user-home-1.1.1.tgz#2b5be23a32b63a7c9deb8d0f28d485724a3df190\"\n+\n+util-deprecate@~1.0.1:\n+ version \"1.0.2\"\n+ resolved \"https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf\"\n+\n+v8flags@^2.0.11:\n+ version \"2.1.1\"\n+ resolved \"https://registry.yarnpkg.com/v8flags/-/v8flags-2.1.1.tgz#aab1a1fa30d45f88dd321148875ac02c0b55e5b4\"\n+ dependencies:\n+ user-home \"^1.1.1\"\n+\n+validate-npm-package-license@^3.0.1:\n+ version \"3.0.1\"\n+ resolved \"https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.1.tgz#2804babe712ad3379459acfbe24746ab2c303fbc\"\n+ dependencies:\n+ spdx-correct \"~1.0.0\"\n+ spdx-expression-parse \"~1.0.0\"\n+\n+which-module@^1.0.0:\n+ version \"1.0.0\"\n+ resolved \"https://registry.yarnpkg.com/which-module/-/which-module-1.0.0.tgz#bba63ca861948994ff307736089e3b96026c2a4f\"\n+\n+which@^1.2.12:\n+ version \"1.2.14\"\n+ resolved \"https://registry.yarnpkg.com/which/-/which-1.2.14.tgz#9a87c4378f03e827cecaf1acdf56c736c01c14e5\"\n+ dependencies:\n+ isexe \"^2.0.0\"\n+\n+wide-align@^1.1.0:\n+ version \"1.1.0\"\n+ resolved \"https://registry.yarnpkg.com/wide-align/-/wide-align-1.1.0.tgz#40edde802a71fea1f070da3e62dcda2e7add96ad\"\n+ dependencies:\n+ string-width \"^1.0.1\"\n+\n+wrap-ansi@^2.0.0:\n+ version \"2.1.0\"\n+ resolved \"https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-2.1.0.tgz#d8fc3d284dd05794fe84973caecdd1cf824fdd85\"\n+ dependencies:\n+ string-width \"^1.0.1\"\n+ strip-ansi \"^3.0.1\"\n+\n+wrappy@1:\n+ version \"1.0.2\"\n+ resolved \"https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f\"\n+\n+xml2js@^0.4.17:\n+ version \"0.4.17\"\n+ resolved \"https://registry.yarnpkg.com/xml2js/-/xml2js-0.4.17.tgz#17be93eaae3f3b779359c795b419705a8817e868\"\n+ dependencies:\n+ sax \">=0.6.0\"\n+ xmlbuilder \"^4.1.0\"\n+\n+xmlbuilder@^4.1.0:\n+ version \"4.2.1\"\n+ resolved \"https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-4.2.1.tgz#aa58a3041a066f90eaa16c2f5389ff19f3f461a5\"\n+ dependencies:\n+ lodash \"^4.0.0\"\n+\n+y18n@^3.2.1:\n+ version \"3.2.1\"\n+ resolved \"https://registry.yarnpkg.com/y18n/-/y18n-3.2.1.tgz#6d15fba884c08679c0d77e88e7759e811e07fa41\"\n+\n+yargs-parser@^4.2.0:\n+ version \"4.2.1\"\n+ resolved \"https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-4.2.1.tgz#29cceac0dc4f03c6c87b4a9f217dd18c9f74871c\"\n+ dependencies:\n+ camelcase \"^3.0.0\"\n+\n+yargs@^6.5.0:\n+ version \"6.6.0\"\n+ resolved \"https://registry.yarnpkg.com/yargs/-/yargs-6.6.0.tgz#782ec21ef403345f830a808ca3d513af56065208\"\n+ dependencies:\n+ camelcase \"^3.0.0\"\n+ cliui \"^3.2.0\"\n+ decamelize \"^1.1.1\"\n+ get-caller-file \"^1.0.1\"\n+ os-locale \"^1.4.0\"\n+ read-pkg-up \"^1.0.1\"\n+ require-directory \"^2.1.1\"\n+ require-main-filename \"^1.0.1\"\n+ set-blocking \"^2.0.0\"\n+ string-width \"^1.0.2\"\n+ which-module \"^1.0.0\"\n+ y18n \"^3.2.1\"\n+ yargs-parser \"^4.2.0\"\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Fixed issue where node reference was being dropped and only last node shared between all handlers |
748,240 | 24.04.2017 21:54:50 | 14,400 | 49b78fca0c6a0a10f3feac36245d415f32ed647f | Added dev version of node-home-assistant | [
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"dependencies\": {\n\"debug\": \"^2.6.3\",\n\"is-string\": \"^1.0.4\",\n- \"node-home-assistant\": \"0.0.3\"\n+ \"node-home-assistant\": \"AYapejian/node-home-assistant#dev-master\"\n},\n\"devDependencies\": {\n\"inspect-process\": \"^0.4.2\"\n"
},
{
"change_type": "MODIFY",
"old_path": "yarn.lock",
"new_path": "yarn.lock",
"diff": "@@ -88,10 +88,10 @@ core-util-is@~1.0.0:\nresolved \"https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7\"\ndebug@^2.2.0, debug@^2.6.3:\n- version \"2.6.3\"\n- resolved \"https://registry.yarnpkg.com/debug/-/debug-2.6.3.tgz#0f7eb8c30965ec08c72accfa0130c8b79984141d\"\n+ version \"2.6.4\"\n+ resolved \"https://registry.yarnpkg.com/debug/-/debug-2.6.4.tgz#7586a9b3c39741c0282ae33445c4e8ac74734fe0\"\ndependencies:\n- ms \"0.7.2\"\n+ ms \"0.7.3\"\ndecamelize@^1.1.1:\nversion \"1.2.0\"\n@@ -108,8 +108,8 @@ error-ex@^1.2.0:\nis-arrayish \"^0.2.1\"\neventsource@^0.2.2:\n- version \"0.2.2\"\n- resolved \"https://registry.yarnpkg.com/eventsource/-/eventsource-0.2.2.tgz#8ac0576cbd16ee83478b3faaf27bdc7b7c8fcca9\"\n+ version \"0.2.3\"\n+ resolved \"https://registry.yarnpkg.com/eventsource/-/eventsource-0.2.3.tgz#30b8f21b40d86968eaeebd199a95072ee54b0df3\"\ndependencies:\noriginal \"^1.0.0\"\n@@ -275,13 +275,13 @@ [email protected], mkdirp@^0.5.1:\ndependencies:\nminimist \"0.0.8\"\[email protected]:\n- version \"0.7.2\"\n- resolved \"https://registry.yarnpkg.com/ms/-/ms-0.7.2.tgz#ae25cf2512b3885a1d95d7f037868d8431124765\"\[email protected]:\n+ version \"0.7.3\"\n+ resolved \"https://registry.yarnpkg.com/ms/-/ms-0.7.3.tgz#708155a5e44e33f5fd0fc53e81d0d40a91be1fff\"\[email protected]:\n+node-home-assistant@AYapejian/node-home-assistant#dev-master:\nversion \"0.0.3\"\n- resolved \"https://registry.yarnpkg.com/node-home-assistant/-/node-home-assistant-0.0.3.tgz#f33afe2bd48203506b02ace1617ea540ae625448\"\n+ resolved \"https://codeload.github.com/AYapejian/node-home-assistant/tar.gz/415e27a69f38c33a19d9c77ed8e4fa64e6201150\"\ndependencies:\naxios \"^0.15.3\"\ndebug \"^2.6.3\"\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Added dev version of node-home-assistant |
748,240 | 24.04.2017 22:04:20 | 14,400 | ac29e9f6a75a3c6c517bb5912caeb9c676e1c365 | Dev version of node-home-assistant (one more time) | [
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"dependencies\": {\n\"debug\": \"^2.6.3\",\n\"is-string\": \"^1.0.4\",\n- \"node-home-assistant\": \"AYapejian/node-home-assistant#dev-master\"\n+ \"node-home-assistant\": \"https://github.com/AYapejian/node-home-assistant.git#dev-master\"\n},\n\"devDependencies\": {\n\"inspect-process\": \"^0.4.2\"\n"
},
{
"change_type": "MODIFY",
"old_path": "yarn.lock",
"new_path": "yarn.lock",
"diff": "@@ -287,6 +287,14 @@ node-home-assistant@AYapejian/node-home-assistant#dev-master:\ndebug \"^2.6.3\"\neventsource \"^0.2.2\"\n+\"node-home-assistant@https://github.com/AYapejian/node-home-assistant.git#dev-master\":\n+ version \"0.0.3\"\n+ resolved \"https://github.com/AYapejian/node-home-assistant.git#415e27a69f38c33a19d9c77ed8e4fa64e6201150\"\n+ dependencies:\n+ axios \"^0.15.3\"\n+ debug \"^2.6.3\"\n+ eventsource \"^0.2.2\"\n+\nnodeflags@^0.0.1:\nversion \"0.0.1\"\nresolved \"https://registry.yarnpkg.com/nodeflags/-/nodeflags-0.0.1.tgz#0e28cedaea9ebe265e97f92b79fb30898245fa17\"\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Dev version of node-home-assistant (one more time) |
748,240 | 19.07.2017 17:53:32 | 14,400 | ecf6f26994927ed4f6a9b9868f5f68bb2d5fd31a | Fixed issue with autocomplete on service node where values were not populating | [
{
"change_type": "MODIFY",
"old_path": "node-service-call/node-service-call.html",
"new_path": "node-service-call/node-service-call.html",
"diff": "const $unknownServiceDiv = $('.unknown-service', $serviceDataDiv);\nconst $knownServiceDiv = $('.known-service', $serviceDataDiv);\n+ const node = this;\n+ $domainField.val(node.service_domain);\n+ $serviceField.val(node.service);\n+ setServicesAndDomains(node);\n+\n+ // Calls the custom api backend defined in the config-server.js node\n+ // TODO: Not sure how this works with node-red if auth is enabled\nfunction setServicesAndDomains(node) {\nreturn $.get('/homeassistant/services')\n- .done(services => {\n+ .then(services => {\nnode.allServices = JSON.parse(services);\nnode.allDomains = node.allServices.map(s => s.domain);\n+\n+ $domainField.autocomplete({\n+ source: node.allDomains,\n+ create: (evt, ui) => updateDomainSelection({ event: evt }),\n+ change: (evt, ui) => updateDomainSelection({ event: evt }),\n+ select: (evt, ui) => updateDomainSelection({ event: evt }),\n+ minLength: 0\n+ }).focus(function() {\n+ $domainField.autocomplete('search');\n+ });\n+\n+ updateDomainSelection({ domainText: node.service_domain || '' });\n+ updateServiceSelection({ serviceText: node.service || '' });\n+\n+ return node;\n})\n.fail((err) => RED.notify(err.responseText, 'error'));\n}\n- function setServicesForDomainAutocomplete(node, services) {\n- function updateServiceSelection(evt, serviceText) {\n+\n+ function updateServiceSelection({ event, serviceText }) {\n+ let selectedServiceText = serviceText;\n+ if ( !selectedServiceText && event) {\n+ selectedServiceText = $(event.target).val();\n+ }\n+\n// If a value selected\n- if (serviceText) {\n- node.selectedService = node.selectedDomain.services[serviceText];\n+ if (selectedServiceText) {\n+\n+ node.selectedService = node.selectedDomain.services[selectedServiceText];\n// If a known service\nif (node.selectedService) {\n- const serviceDesc = node.selectedService.description;\n+ const serviceDesc = node.selectedService.description ?\n+ node.selectedService.description : 'No description provided by home assistant';\nconst fields = node.selectedService.fields;\nlet tableRows = Object.keys(fields).reduce((tRows, k) => {\nreturn tRows;\n}, []);\n+\ntableRows = (tableRows.length > 0)\n? tableRows.join('')\n: '';\n// Add table and description for service and service fields\n$serviceDescDiv.html(serviceDesc);\n+ $('#service-data-desc .title').html(node.selectedDomain.domain + '.' + selectedServiceText)\n+ if (tableRows) {\n+ $(\"#service-data-table\").show();\n$serviceDataTableBody.html(tableRows);\n+ } else {\n+ $(\"#service-data-table\").hide();\n+ $serviceDescDiv.append('<p>No fields documented by home-assistant<p>');\n+ }\n$unknownServiceDiv.hide();\n$knownServiceDiv.show();\n+ debugger;\n} else {\n+ debugger;\n// Hide service data fields and desc\n$unknownServiceDiv.show();\n$knownServiceDiv.hide();\n}\n+ function updateDomainSelection({ event, domainText }) {\n+ let selectedDomainText = domainText;\n+ if ( !selectedDomainText && event) { selectedDomainText = $(event.target).val(); }\n+\n+ const knownDomain = (node.allDomains.indexOf(selectedDomainText) > -1);\n+ node.selectedDomain = knownDomain\n+ ? node.allServices.find(s => (s.domain === selectedDomainText))\n+ : node.selectedDomain = { services: {} };\n+\n$serviceField.autocomplete({\n- source: Object.keys(services),\n- create: (evt, ui) => updateServiceSelection(evt, $(evt.target).val()),\n- change: (evt, ui) => updateServiceSelection(evt, $(evt.target).val()),\n- select: (evt, ui) => updateServiceSelection(evt, $(evt.target).val()),\n- focus: (evt, ui) => updateServiceSelection(evt, ui.item.label),\n+ source: Object.keys(node.selectedDomain.services),\n+ create: (evt, ui) => updateServiceSelection({ event: evt }),\n+ change: (evt, ui) => updateServiceSelection({ event: evt }),\n+ select: (evt, ui) => updateServiceSelection({ event: evt }),\n+ focus: (evt, ui) => updateServiceSelection({ event: evt }),\nminLength: 0\n})\n.focus(function() {\n$serviceField.autocomplete('search');\n- });;\n- }\n-\n- function initDomainAutocomplete(node) {\n-\n- function updateDomainSelection(evt, domainText) {\n- const knownDomain = (node.allDomains.indexOf(domainText) > -1);\n-\n- if (knownDomain) {\n- node.selectedDomain = node.allServices.find(s => (s.domain === domainText));\n- } else {\n- node.selectedDomain = { services: {} };\n- }\n-\n- setServicesForDomainAutocomplete(node, node.selectedDomain.services);\n- }\n-\n- $domainField.autocomplete({\n- source: node.allDomains,\n- create: (evt, ui) => updateDomainSelection(evt, $(evt.target).val()),\n- change: (evt, ui) => updateDomainSelection(evt, $(evt.target).val()),\n- select: (evt, ui) => updateDomainSelection(evt, $(evt.target).val()),\n- focus: (evt, ui) => updateDomainSelection(evt, ui.item.label),\n- minLength: 0\n- }).focus(function() {\n- $domainField.autocomplete('search');\n});\n}\n-\n- // ***********************************\n- // ENTRY POINT\n- // ***********************************\n- const node = this;\n- $domainField.val(node.service_domain);\n- $serviceField.val(node.service);\n-\n-\n- setServicesAndDomains(node).then(() => initDomainAutocomplete(node));\n},\noneditsave: function() {\nthis.service_domain = $(\"#service_domain\").val();\n</div>\n<div id=\"service-data-desc\" class=\"form-row\">\n- <h4>Service Data Fields</h4>\n+ <h4>\n+ Service: <span class=\"title\"></span>\n+ </h4>\n<div class=\"unknown-service\">Unknown Service</div>\n<div class=\"known-service\">\n<p class='service-description'></p>\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Fixed issue with autocomplete on service node where values were not populating |
748,240 | 20.07.2017 17:52:05 | 14,400 | 86c436a375489a093df6be2f15d29d4b0e0cc973 | Bug with typo on require | [
{
"change_type": "MODIFY",
"old_path": "node-current-state/node-current-state.html",
"new_path": "node-current-state/node-current-state.html",
"diff": "}\n},\noneditprepare: function () {\n+ // * **************************************************\n+ // TODO: Put this autocomplete funtionality in all entity_id nodes\n+ // * **************************************************\n// Set current value to input\nconst $entityIdField = $('#entity_id');\n$entityIdField.val(this.entity_id);\n"
},
{
"change_type": "MODIFY",
"old_path": "node-service-call/node-service-call.js",
"new_path": "node-service-call/node-service-call.js",
"diff": "@@ -12,7 +12,7 @@ const _int = {\ntry { data = JSON.parse(config.data); }\ncatch (e) {\ndebug('JSON parse error');\n- debug(require('utils').inspect(config.data));\n+ debug(require('util').inspect(config.data));\n}\n}\nnode.data = data;\n@@ -25,7 +25,7 @@ const _int = {\nnode.status(show);\nstatus = !status;\n}, 100);\n- setTimeout(() => { clearInterval(flash); node.status({}); }, 1000);\n+ setTimeout(() => { clearInterval(flash); node.status({}); }, 2000);\n},\nonInput: function(msg, node) {\nconst p = msg.payload;\n@@ -38,7 +38,7 @@ const _int = {\ntry { data = JSON.parse(p.data) }\ncatch (e) {\ndebug('JSON parse error');\n- debug(require('utils').inspect(config.data));\n+ debug(require('util').inspect(config.data));\n}\n}\ndata = Object.assign({}, node.data, data);\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Bug with typo on require |
748,240 | 21.07.2017 14:53:49 | 14,400 | 2e35fb1ceb7a677d676d2610c66a8cae06a875f0 | Use abstracted methods to fetch states,events,and permissions in config node | [
{
"change_type": "MODIFY",
"old_path": "config-server/config-server.js",
"new_path": "config-server/config-server.js",
"diff": "@@ -15,7 +15,6 @@ module.exports = function(RED) {\nnode.url = config.url;\nnode.pass = config.pass;\n- debugger;\nif (node.url && !node.homeAssistant) {\nconst ha = node.homeAssistant = new HomeAssistant({ baseUrl: node.url, apiPass: node.pass });\nnode.api = ha.api;\n@@ -24,19 +23,35 @@ module.exports = function(RED) {\n// All known entities derived from current state\nRED.httpAdmin.get('/homeassistant/entities', function (req, res, next) {\n- res.end(JSON.stringify(Object.keys(node.homeAssistant.states)));\n+ return node.homeAssistant.getStates()\n+ .then(states => {\n+ const entities = JSON.stringify(Object.keys(states))\n+ return res.end(entities);\n+ })\n});\n// The node-home-assistant module tracks state for us, just return the latest object\nRED.httpAdmin.get('/homeassistant/states', function (req, res, next) {\n- res.end(JSON.stringify(node.homeAssistant.states));\n+ return node.homeAssistant.getStates()\n+ .then(states => {\n+ const resStates = JSON.stringify(states)\n+ return res.end(resStates);\n+ });\n});\n// All known services available\nRED.httpAdmin.get('/homeassistant/services', function (req, res, next) {\n- res.end(JSON.stringify(node.homeAssistant.availableServices));\n+ return node.homeAssistant.getServices()\n+ .then(services => {\n+ const resServices = JSON.stringify(services)\n+ return res.end(resServices);\n+ });\n});\n// All known events that could be incoming\nRED.httpAdmin.get('/homeassistant/events', function (req, res, next) {\n- res.end(JSON.stringify(node.homeAssistant.availableEvents));\n+ return node.homeAssistant.getEvents()\n+ .then(events => {\n+ const resEvents = JSON.stringify(events)\n+ return res.end(resEvents);\n+ });\n});\n}\nRED.nodes.registerType('server', ConfigServer);\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Use abstracted methods to fetch states,events,and permissions in config node |
748,240 | 21.07.2017 23:56:50 | 14,400 | 8774c00225f4238cfee1822b709c04f8c15d9104 | Fixed issue where connection status was not being set correctly on partial deploy of nodes | [
{
"change_type": "MODIFY",
"old_path": "node-server-events/node-server-events.html",
"new_path": "node-server-events/node-server-events.html",
"diff": "color: '#038FC7',\ndefaults: {\nname: { value: '' },\n- server: { value: '', type: 'server' }\n+ server: { value: '', type: 'server', required: true }\n},\ninputs: 0,\noutputs: 1,\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-events/node-server-events.js",
"new_path": "node-server-events/node-server-events.js",
"diff": "@@ -6,10 +6,6 @@ const _int = {\nconst settings = {}\nreturn settings;\n},\n- setStatus: function setStatus(isConnected, node) {\n- if (isConnected) { node.status({ fill: 'green', shape: 'ring', text: 'Connected' }); }\n- else { node.status({ fill: 'red', shape: 'ring', text: 'Disconnected' }) }\n- },\ngetHandlers: function(node) {\nreturn {\nonEvent: (evt) => {\n@@ -26,18 +22,18 @@ const _int = {\nmodule.exports = function(RED) {\nfunction EventsAll(config) {\n- RED.nodes.createNode(this, config);\nconst node = this;\n+ RED.nodes.createNode(node, config);\n+\nnode._state = {};\n- _int.node = node;\nnode.settings = _int.getSettings(config);\n-\nnode.server = RED.nodes.getNode(config.server);\n- nodeUtils.setConnectionStatus(node, false);\n- const handlers = _int.getHandlers(node);\n// If the event source was setup start listening for events\nif (node.server) {\n+ nodeUtils.setConnectionStatus(node, node.server.events.connected);\n+\n+ const handlers = _int.getHandlers(node);\nconst eventsClient = node.server.events;\neventsClient.on('ha_events:all', handlers.onEvent);\n@@ -45,13 +41,15 @@ module.exports = function(RED) {\neventsClient.on('ha_events:open', handlers.onOpen);\neventsClient.on('ha_events:error', handlers.onError);\n- this.on('close', function(done) {\n+ node.on('close', function(done) {\neventsClient.removeListener('ha_events:all', handlers.onEvent);\neventsClient.removeListener('ha_events:close', handlers.onClose);\neventsClient.removeListener('ha_events:open', handlers.onOpen);\neventsClient.removeListener('ha_events:error', handlers.onError);\ndone();\n});\n+ } else {\n+ nodeUtils.setConnectionStatus(node, false);\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-state-changed/node-server-state-changed.html",
"new_path": "node-server-state-changed/node-server-state-changed.html",
"diff": "color: '#038FC7',\ndefaults: {\nname: { value: '' },\n- server: { value: '', type: 'server' },\n+ server: { value: '', type: 'server', required: true },\nentityidfilter: { value: '' },\nentityidblacklist: { value: 'sensor.time,sensor.date__time,dark_sky,sun.sun' },\nskipifstate: { value: '' }\n<input type=\"text\" id=\"node-input-entityidfilter\" placeholder=\"binary_sensor\"/>\n</div>\n-\n-\n-\n<div class=\"form-row\">\n<label for=\"entity_id\"><i class=\"fa fa-cube\"></i> Entity ID</label>\n<input type=\"text\" id=\"entity_id\">\n</div>\n-\n-\n<div class=\"form-row\">\n<label for=\"node-input-entityidblacklist\"><i class=\"fa fa-filter\"></i> EntityID Blacklist</label>\n<input type=\"text\" id=\"node-input-entityidblacklist\" />\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-state-changed/node-server-state-changed.js",
"new_path": "node-server-state-changed/node-server-state-changed.js",
"diff": "@@ -73,18 +73,18 @@ const _int = {\nmodule.exports = function(RED) {\nfunction EventsStateChange(config) {\n- RED.nodes.createNode(this, config);\nconst node = this;\n- node.settings = _int.getSettings(config);\n- node._state = {};\n+ RED.nodes.createNode(node, config);\n+ node._state = {};\n+ node.settings = _int.getSettings(config);\nnode.server = RED.nodes.getNode(config.server);\n- nodeUtils.setConnectionStatus(node, false);\n- const handlers = _int.getHandlers(node);\n// If the event source was setup start listening for events\n- debugger;\nif (node.server) {\n+ nodeUtils.setConnectionStatus(node, node.server.events.connected);\n+\n+ const handlers = _int.getHandlers(node);\nconst eventsClient = node.server.events;\neventsClient.on('ha_events:state_changed', handlers.onStateChanged);\n@@ -99,6 +99,8 @@ module.exports = function(RED) {\neventsClient.removeListener('ha_events:error', handlers.onError);\ndone();\n});\n+ } else {\n+ nodeUtils.setConnectionStatus(node, false);\n}\n}\nRED.nodes.registerType('server-state-changed', EventsStateChange);\n"
},
{
"change_type": "MODIFY",
"old_path": "node-service-call/node-service-call.html",
"new_path": "node-service-call/node-service-call.html",
"diff": "// when trying to be used as a default below.\ndefaults: {\nname: { value: '' },\n- server: { value: '', type: 'server' },\n+ server: { value: '', type: 'server', required: true },\nservice_domain: { value: '' },\nservice: { value: '' },\ndata: { value: '' }\n"
},
{
"change_type": "MODIFY",
"old_path": "package-lock.json",
"new_path": "package-lock.json",
"diff": "\"dev\": true\n},\n\"node-home-assistant\": {\n- \"version\": \"git+https://github.com/AYapejian/node-home-assistant.git#415e27a69f38c33a19d9c77ed8e4fa64e6201150\",\n+ \"version\": \"git+https://github.com/AYapejian/node-home-assistant.git#514540ea4524988eaaf9e930fe3a32fed0e595cf\",\n\"requires\": {\n\"axios\": \"0.15.3\",\n\"debug\": \"2.6.8\",\n"
},
{
"change_type": "MODIFY",
"old_path": "utils/node-utils.js",
"new_path": "utils/node-utils.js",
"diff": "+'use strict';\nconst nodeUtils = module.exports = {};\nconst dateFns = require('date-fns')\nnodeUtils.setConnectionStatus = function (node, isConnected, err) {\n+\n+ console.log (`status isConnected: ${node.name}, ${isConnected}`);\n// Only update if state changes and we don't have an error to display\nif (!err && node._state.isConnected === isConnected) { return; }\nif (err) { node.error(`Connection error occured with the home-assistant server: ${JSON.stringify(err)}`); }\nif (isConnected) { node.status({ fill: 'green', shape: 'ring', text: 'Connected' }); }\nelse {\n- const statusMsg = (err) ? `Disconnected (error encountered)` : 'Disconnected';\n+ const statusMsg = (err) ? 'Disconnected (error encountered)' : 'Disconnected';\nnode.status({ fill: 'red', shape: 'ring', text: statusMsg });\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Fixed issue where connection status was not being set correctly on partial deploy of nodes |
748,240 | 22.07.2017 00:45:25 | 14,400 | 2d177aa71afd1c812a404861f0ba0cf6ad9eef42 | state changed node now has autocomplete helpers for filters | [
{
"change_type": "MODIFY",
"old_path": "node-server-state-changed/node-server-state-changed.html",
"new_path": "node-server-state-changed/node-server-state-changed.html",
"diff": "name: { value: '' },\nserver: { value: '', type: 'server', required: true },\nentityidfilter: { value: '' },\n- entityidblacklist: { value: 'sensor.time,sensor.date__time,dark_sky,sun.sun' },\n+ entityidblacklist: { value: 'sensor.time,sensor.date__time,sun.sun' },\nskipifstate: { value: '' }\n},\ninputs: 0,\npaletteLabel: 'events: state',\nlabel: function() { return this.name || `state_changed: ${this.entityidfilter || 'all entities'}` },\noneditprepare: function () {\n- // * **************************************************\n- // TODO: Put this autocomplete funtionality in all entity_id nodes\n- // * **************************************************\n- // Set current value to input\n- const $entityIdField = $('#entity_id');\n- $entityIdField.val(this.entity_id);\n+ const $entityIdField = $('#node-input-entityidfilter');\n+ const $entityIdBlacklistField = $('#node-input-entityidblacklist');\n+ const $serverField = $('#node-input-server');\n+ $entityIdField.val(this.entityidfilter);\n+ $entityIdBlacklistField.val(this.entityidblacklist);\n- $.get('/homeassistant/entities')\n- .done((entities) => {\n+ const setupAutocomplete = () => {\n+ debugger;\n+ if (this.server) {\n+ $.get('/homeassistant/entities').done((entities) => {\nthis.availableEntities = JSON.parse(entities);\n+ $entityIdField.autocomplete({ source: this.availableEntities, minLength: 0 });\n+ $entityIdBlacklistField.autocomplete({ source: this.availableEntities, minLength: 0 });\n- $entityIdField.autocomplete({\n- source: this.availableEntities,\n- minLength: 0,\n- change: (evt,ui) => {\n- const validSelection = (this.availableEntities.indexOf($(evt.target).val()) > -1);\n- if (validSelection) { $(evt.target).removeClass('input-error'); }\n- else { $(evt.target).addClass('input-error'); }\n- }\n- });\n-\n- const validSelection = (this.availableEntities.indexOf(this.entity_id) > -1);\n- if (validSelection) { $entityIdField.removeClass('input-error'); }\n- else { $entityIdField.addClass('input-error'); }\n})\n.fail((err) => RED.notify(err.responseText, 'error'));\n+ }\n+ };\n+\n+ $serverField.change(setupAutocomplete);\n+ setupAutocomplete();\n},\n- oneditsave: function() { this.entity_id = $(\"#entity_id\").val(); }\n+ oneditsave: function() {\n+ this.entityidfilter = $(\"#node-input-entityidfilter\").val();\n+ this.this.entityidblacklist = $(\"#node-input-entityidblacklist\").val();\n+ }\n});\n</script>\n<input type=\"text\" id=\"node-input-entityidfilter\" placeholder=\"binary_sensor\"/>\n</div>\n- <div class=\"form-row\">\n- <label for=\"entity_id\"><i class=\"fa fa-cube\"></i> Entity ID</label>\n- <input type=\"text\" id=\"entity_id\">\n- </div>\n-\n<div class=\"form-row\">\n<label for=\"node-input-entityidblacklist\"><i class=\"fa fa-filter\"></i> EntityID Blacklist</label>\n<input type=\"text\" id=\"node-input-entityidblacklist\" />\n</script>\n<script type=\"text/x-red\" data-help-name=\"server-state-changed\">\n- <p>Outputs 'state_changed' event types sent from Home Assistant</p>\n- <p>NOTE: The filters are simple substring matches, you can add multiple by comma seperated list and each entry will be matched separately</p>\n+ <p class=\"ha-description\">Outputs 'state_changed' event types sent from Home Assistant</p>\n+\n+ <p class=\"ha-subdescription\">The autocomplete will open to allow easier selection in the case you want a specific entity however the actual match is a substring match so no validation is done</p>\n+ <p class=\"ha-additional-info\">NOTE: You can add multiple string matches by comma separated list and each entry will be matched separately</p>\n+\n+ <h4 class=\"ha-title\">Configuration:</h4>\n+ <table class=\"ha-table\" style=\"width: 100%;\" border=\"1\" cellpadding=\"10\">\n+ <tbody>\n+ <tr> <td>Entity ID Filter</td> <td>CSV substring matches for entity_id field</td> </tr>\n+ <tr> <td>Entity ID Blacklist</td> <td>CSV substring match for excluding entities</td> </tr>\n+ <tr> <td>Skip If State</td> <td>If the new_state === this setting then skip sending </tr>\n+ </tbody>\n+ </table>\n+\n<br/>\n- <p>Entity ID Filter: Only state changes that subtring match entity_id field</p>\n- <p>Entity ID Blacklist: Exclude state changes that substring match entity_id</p>\n- <p>Skip If State: If the new_state === this setting then do -not- send the event</p>\n- <p>The outputted message object contains the following data, underscored values are straight from home assistant</p>\n- <table style=\"width: 100%;\" border=\"1\" cellpadding=\"10\">\n+ <h4 class=\"ha-title\">Output Object:</h4>\n+ <table class=\"ha-table\" style=\"width: 100%;\" border=\"1\" cellpadding=\"10\">\n<tbody>\n- <tr> <td>topic</td> <td>entity_id</td> </tr>\n- <tr> <td>payload</td> <td>event.new_state.state</td> </tr>\n- <tr> <td>event</td> <td>original event object</td> </tr>\n+ <tr> <td>topic</td> <td>entity_id (e.g.: sensor.bedroom_temp)</td> </tr>\n+ <tr> <td>payload</td> <td>event.new_state.state (e.g.: 'on', 'off', '88.5', 'home', 'not_home')</td> </tr>\n+ <tr> <td>event</td> <td>original event object from homeassistant</td> </tr>\n</tbody>\n</table>\n</script>\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-state-changed/node-server-state-changed.js",
"new_path": "node-server-state-changed/node-server-state-changed.js",
"diff": "@@ -11,11 +11,6 @@ const _int = {\nreturn settings;\n},\n- shouldSkipNoChange: function shouldSkipNoChange(e, node) {\n- if (!e.event || !e.event.old_state || !e.event.new_state) { return false; }\n- const shouldSkip = (e.event.old_state.state === e.event.new_state.state);\n- return shouldSkip;\n- },\nshouldSkipIfState: function shouldSkipIfState(e, skipIfState) {\nif (!skipIfState) { return false; }\nconst shouldSkip = (skipIfState === e.event.new_state.state);\n@@ -46,7 +41,6 @@ const _int = {\n},\n/* eslint-disable consistent-return */\nonIncomingMessage: function onIncomingMessage(evt, node) {\n- if (_int.shouldSkipNoChange(evt, node)) { return null; }\nif (_int.shouldSkipIfState(evt, node.settings.skipIfState)) { return null; }\nconst { entity_id, event } = evt;\n"
},
{
"change_type": "MODIFY",
"old_path": "utils/node-utils.js",
"new_path": "utils/node-utils.js",
"diff": "@@ -3,10 +3,6 @@ const nodeUtils = module.exports = {};\nconst dateFns = require('date-fns')\nnodeUtils.setConnectionStatus = function (node, isConnected, err) {\n-\n- console.log (`status isConnected: ${node.name}, ${isConnected}`);\n- // Only update if state changes and we don't have an error to display\n- if (!err && node._state.isConnected === isConnected) { return; }\nif (err) { node.error(`Connection error occured with the home-assistant server: ${JSON.stringify(err)}`); }\nif (isConnected) { node.status({ fill: 'green', shape: 'ring', text: 'Connected' }); }\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | state changed node now has autocomplete helpers for filters |
748,240 | 22.07.2017 01:05:19 | 14,400 | 3ff1eff95a538dcb554164761e87a224656258da | Fixed issue with autocomplete | [
{
"change_type": "MODIFY",
"old_path": "node-server-state-changed/node-server-state-changed.html",
"new_path": "node-server-state-changed/node-server-state-changed.html",
"diff": "$entityIdField.val(this.entityidfilter);\n$entityIdBlacklistField.val(this.entityidblacklist);\n- const setupAutocomplete = () => {\n- debugger;\n- if (this.server) {\n- $.get('/homeassistant/entities').done((entities) => {\n- this.availableEntities = JSON.parse(entities);\n- $entityIdField.autocomplete({ source: this.availableEntities, minLength: 0 });\n- $entityIdBlacklistField.autocomplete({ source: this.availableEntities, minLength: 0 });\n+ const setupAutocomplete = (node) => {\n+ const selectedServer = $serverField.val();\n+ // A home assistant server is selected in the node config\n+ if (node.server || (selectedServer && selectedServer !== '_ADD_')) {\n+ $.get('/homeassistant/entities').done((entities) => {\n+ node.availableEntities = JSON.parse(entities);\n+ $entityIdField.autocomplete({ source: node.availableEntities, minLength: 0 });\n+ $entityIdBlacklistField.autocomplete({ source: node.availableEntities, minLength: 0 });\n})\n.fail((err) => RED.notify(err.responseText, 'error'));\n}\n};\n- $serverField.change(setupAutocomplete);\n- setupAutocomplete();\n+ $serverField.change(() => setupAutocomplete(this));\n},\noneditsave: function() {\nthis.entityidfilter = $(\"#node-input-entityidfilter\").val();\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Fixed issue with autocomplete |
748,240 | 22.07.2017 01:31:21 | 14,400 | 193b8adce953e66248b756bb016a652cac3f5614 | Removed the blacklist option for server state change node | [
{
"change_type": "MODIFY",
"old_path": "node-server-state-changed/node-server-state-changed.html",
"new_path": "node-server-state-changed/node-server-state-changed.html",
"diff": "name: { value: '' },\nserver: { value: '', type: 'server', required: true },\nentityidfilter: { value: '' },\n- entityidblacklist: { value: 'sensor.time,sensor.date__time,sun.sun' },\n- skipifstate: { value: '' }\n+ haltifstate: { value: '' }\n},\ninputs: 0,\noutputs: 1,\nlabel: function() { return this.name || `state_changed: ${this.entityidfilter || 'all entities'}` },\noneditprepare: function () {\nconst $entityIdField = $('#node-input-entityidfilter');\n- const $entityIdBlacklistField = $('#node-input-entityidblacklist');\nconst $serverField = $('#node-input-server');\n$entityIdField.val(this.entityidfilter);\n- $entityIdBlacklistField.val(this.entityidblacklist);\nconst setupAutocomplete = (node) => {\nconst selectedServer = $serverField.val();\n$.get('/homeassistant/entities').done((entities) => {\nnode.availableEntities = JSON.parse(entities);\n$entityIdField.autocomplete({ source: node.availableEntities, minLength: 0 });\n- $entityIdBlacklistField.autocomplete({ source: node.availableEntities, minLength: 0 });\n})\n.fail((err) => RED.notify(err.responseText, 'error'));\n}\n},\noneditsave: function() {\nthis.entityidfilter = $(\"#node-input-entityidfilter\").val();\n- this.this.entityidblacklist = $(\"#node-input-entityidblacklist\").val();\n}\n});\n</script>\n</div>\n<div class=\"form-row\">\n- <label for=\"node-input-entityidblacklist\"><i class=\"fa fa-filter\"></i> EntityID Blacklist</label>\n- <input type=\"text\" id=\"node-input-entityidblacklist\" />\n- </div>\n-\n- <div class=\"form-row\">\n- <label for=\"node-input-skipifstate\"><i class=\"fa fa-hand-paper-o\"></i> Halt If State</label>\n- <input type=\"text\" id=\"node-input-skipifstate\" />\n+ <label for=\"node-input-haltifstate\"><i class=\"fa fa-hand-paper-o\"></i> Halt If State</label>\n+ <input type=\"text\" id=\"node-input-haltifstate\" />\n</div>\n</script>\n<table class=\"ha-table\" style=\"width: 100%;\" border=\"1\" cellpadding=\"10\">\n<tbody>\n<tr> <td>Entity ID Filter</td> <td>CSV substring matches for entity_id field</td> </tr>\n- <tr> <td>Entity ID Blacklist</td> <td>CSV substring match for excluding entities</td> </tr>\n- <tr> <td>Skip If State</td> <td>If the new_state === this setting then skip sending </tr>\n+ <tr> <td>Halt If State</td> <td>If the new_state === this setting then skip sending </tr>\n</tbody>\n</table>\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-state-changed/node-server-state-changed.js",
"new_path": "node-server-state-changed/node-server-state-changed.js",
"diff": "@@ -5,45 +5,25 @@ const _int = {\ngetSettings: function getSettings(config) {\nconst settings = {\nentityIdFilter: config.entityidfilter ? config.entityidfilter.split(',').map(f => f.trim()): null,\n- entityIdBlacklist: config.entityidblacklist ? config.entityidblacklist.split(',').map(f => f.trim()) : null,\n- skipIfState: config.skipifstate\n+ haltIfState: config.haltifstate ? config.haltifstate.trim() : null\n};\n-\nreturn settings;\n},\n- shouldSkipIfState: function shouldSkipIfState(e, skipIfState) {\n- if (!skipIfState) { return false; }\n- const shouldSkip = (skipIfState === e.event.new_state.state);\n- return shouldSkip;\n+ shouldHaltIfState: function shouldHaltIfState(haEvent, haltIfState) {\n+ if (!haltIfState) { return false; }\n+ const shouldHalt = (haltIfState === haEvent.new_state.state);\n+ return shouldHalt;\n},\n- shouldIncludeEvent: function shouldIncludeEvent(entityId, { entityIdFilter, entityIdBlacklist }) {\n- // If neither filter is sent just send the event on\n- if (!entityIdFilter && !entityIdBlacklist) { return true; }\n-\n- const findings = {};\n- // If include filter is null then set to found\n- if (!entityIdFilter) { findings.included = true; }\n-\n- if (entityIdFilter && entityIdFilter.length) {\n- const found = entityIdFilter.filter(iStr => (entityId.indexOf(iStr) >= 0));\n- findings.included = (found.length > 0);\n- }\n-\n- // If blacklist is null set exluded false\n- if (!entityIdBlacklist) { findings.excluded = false; }\n-\n- if (entityIdBlacklist && entityIdBlacklist.length) {\n- const found = entityIdBlacklist.filter(blStr => (entityId.indexOf(blStr) >= 0));\n- findings.excluded = (found.length > 0);\n- }\n-\n- return findings.included && !findings.excluded;\n+ shouldIncludeEvent: function shouldIncludeEvent(entityId, { entityIdFilter }) {\n+ if (!entityIdFilter) { return true; }\n+ const found = entityIdFilter.filter(filterStr => (entityId.indexOf(filterStr) >= 0));\n+ return found.length > 0;\n},\n/* eslint-disable consistent-return */\nonIncomingMessage: function onIncomingMessage(evt, node) {\n- if (_int.shouldSkipIfState(evt, node.settings.skipIfState)) { return null; }\n-\nconst { entity_id, event } = evt;\n+ if (_int.shouldHaltIfState(event, node.settings.haltIfState)) { return null; }\n+\nconst msg = {\ntopic: entity_id,\npayload: event.new_state.state,\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Removed the blacklist option for server state change node |
748,240 | 12.08.2017 00:48:16 | 14,400 | f45437c8c130c26a0c4ccc00afa580259cd6e631 | Fixed some bugs, added some logging | [
{
"change_type": "MODIFY",
"old_path": ".eslintrc",
"new_path": ".eslintrc",
"diff": "\"mocha\": true,\n\"es6\": true\n},\n- \"parserOptions\": {\n- \"ecmaVersion\": 2017,\n- \"ecmaFeatures\": {\n- \"arrowFunctions\": true,\n- \"binaryLiterals\": true,\n- \"blockBindings\": true,\n- \"classes\": true,\n- \"defaultParams\": true,\n- \"destructuring\": true,\n- \"forOf\": true,\n- \"generators\": true,\n- \"modules\": true,\n- \"objectLiteralComputedProperties\": true,\n- \"objectLiteralDuplicateProperties\": true,\n- \"objectLiteralShorthandMethods\": true,\n- \"objectLiteralShorthandProperties\": true,\n- \"octalLiterals\": true,\n- \"regexUFlag\": true,\n- \"regexYFlag\": true,\n- \"spread\": true,\n- \"superInFunctions\": true,\n- \"templateStrings\": true,\n- \"unicodeCodePointEscapes\": true,\n- \"globalReturn\": true,\n- \"jsx\": true\n- }\n- },\n\"rules\": {\n// Strict mode to support babel\n\"strict\": 2, // controls location of Use Strict Directives. 0: required by `babel-eslint`\n"
},
{
"change_type": "MODIFY",
"old_path": "node-current-state/node-current-state.js",
"new_path": "node-current-state/node-current-state.js",
"diff": "@@ -21,11 +21,14 @@ const _int = {\nreturn null;\n}\n- if (node.halt_if && (currentState.state !== node.halt_if)) {\n- node.send({ payload: currentState });\n- } else if (!node.halt_if) {\n- node.send({ payload: currentState });\n+ const shouldHaltIfState = node.halt_if && (currentState.state === node.halt_if);\n+ node.debug(`Get current state: Found entity: ${entity_id}, with state: ${currentState.state}`);\n+ if (shouldHaltIfState) {\n+ node.debug(`Get current state: halting processing due to current state of ${entity_id} matches \"halt if state\" option`);\n+ return null;\n}\n+\n+ node.send({ payload: currentState });\n}\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "node-server-state-changed/node-server-state-changed.js",
"new_path": "node-server-state-changed/node-server-state-changed.js",
"diff": "@@ -22,7 +22,16 @@ const _int = {\n/* eslint-disable consistent-return */\nonIncomingMessage: function onIncomingMessage(evt, node) {\nconst { entity_id, event } = evt;\n- if (_int.shouldHaltIfState(event, node.settings.haltIfState)) { return null; }\n+ // TODO: Infrequent issue seen where event encountered without new_state, logging to pick up info\n+ if (!event || !event.new_state) {\n+ node.debug('Warning, event encountered without new_state');\n+ node.debug(JSON.stringify(event));\n+ node.warn(event);\n+ } else {\n+ const shouldHaltIfState = _int.shouldHaltIfState(event, node.settings.haltIfState);\n+ const shouldIncludeEvent = _int.shouldIncludeEvent(entity_id, node.settings);\n+\n+ if (shouldHaltIfState) { return null; }\nconst msg = {\ntopic: entity_id,\n@@ -30,10 +39,12 @@ const _int = {\nevent: event\n};\n- if (_int.shouldIncludeEvent(entity_id, node.settings)) {\n+ if (shouldIncludeEvent) {\n+ node.debug(`Incoming state event: entity_id: ${event.entity_id}, new_state: ${event.new_state.state}, old_state: ${event.old_state.state}`);\nnodeUtils.flashStatus(node, { status: { fill: 'green', shape: 'ring' }});\nnode.send(msg);\n}\n+ }\n},\ngetHandlers: function(node) {\nreturn {\n"
},
{
"change_type": "MODIFY",
"old_path": "node-service-call/node-service-call.html",
"new_path": "node-service-call/node-service-call.html",
"diff": "server: { value: '', type: 'server', required: true },\nservice_domain: { value: '' },\nservice: { value: '' },\n- data: { value: '' }\n+ data: { value: '', validate: function(v) {\n+ try { JSON.parse(v); return true; }\n+ catch (e) { return false; }\n+ } }\n},\noneditprepare: function () {\nconst $domainField = $('#service_domain');\n"
},
{
"change_type": "MODIFY",
"old_path": "node-service-call/node-service-call.js",
"new_path": "node-service-call/node-service-call.js",
"diff": "'use strict';\n-const debug = require('debug')('home-assistant:service-call');\nconst isString = require('is-string');\n@@ -11,8 +10,8 @@ const _int = {\nif (isString(config.data)) {\ntry { data = JSON.parse(config.data); }\ncatch (e) {\n- debug('JSON parse error');\n- debug(require('util').inspect(config.data));\n+ node.debug('JSON parse error');\n+ node.debug(require('util').inspect(config.data));\n}\n}\nnode.data = data;\n@@ -35,19 +34,22 @@ const _int = {\nlet data = p.data || {};\nif (isString(data)) {\n- try { data = JSON.parse(p.data) }\n+ try { data = JSON.parse(data) }\ncatch (e) {\n- debug('JSON parse error');\n- debug(require('util').inspect(config.data));\n+ node.debug('JSON parse error');\n+ node.debug(require('util').inspect(data));\n}\n}\n+ debugger;\ndata = Object.assign({}, node.data, data);\nif (!domain || !service) {\nnode.warn('Domain or Service not set, skipping call service');\n} else {\n+ debugger;\n_int.flashStatus(node);\n- debug(`Calling Service: ${domain}:${service} -- ${JSON.stringify(data)}`);\n+ node.debug(`Calling Service: ${domain}:${service} -- ${JSON.stringify(data)}`);\n+\nnode.server.api.callService(domain, service, data)\n.catch(err => {\nnode.warn('Error calling service, home assistant api error');\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Fixed some bugs, added some logging |
748,240 | 22.08.2017 13:36:07 | 14,400 | 17ce72cf2949472a15fdb2a27bc8f69348f7a37c | New node-home-assistant version | [
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"date-fns\": \"^1.28.5\",\n\"debug\": \"^2.6.3\",\n\"is-string\": \"^1.0.4\",\n- \"node-home-assistant\": \"https://github.com/AYapejian/node-home-assistant.git#dev-master\"\n+ \"node-home-assistant\": \"0.1.0\"\n},\n\"devDependencies\": {\n\"eslint\": \"^4.2.0\",\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | New node-home-assistant version |
748,245 | 23.01.2018 09:55:44 | 28,800 | 7d6b1bf4de7a9d16fdaa746f692b3354e9b09220 | Make sure old_state is not null
Related to | [
{
"change_type": "MODIFY",
"old_path": "node-server-state-changed/node-server-state-changed.js",
"new_path": "node-server-state-changed/node-server-state-changed.js",
"diff": "@@ -43,7 +43,11 @@ const _int = {\n};\nif (shouldIncludeEvent) {\n+ if (event.old_state) {\nnode.debug(`Incoming state event: entity_id: ${event.entity_id}, new_state: ${event.new_state.state}, old_state: ${event.old_state.state}`);\n+ } else {\n+ node.debug(`Incoming state event: entity_id: ${event.entity_id}, new_state: ${event.new_state.state}`);\n+ }\nnodeUtils.flashAttentionStatus(node, { appendMsg: event.new_state.state });\nnode.send(msg);\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Make sure old_state is not null
Related to #5 |
748,240 | 28.01.2018 15:50:39 | 18,000 | 7107e9fd72a28044961395359acf98c6e4e354e0 | Added examples of the current state node to the dev environment in docker node-red | [
{
"change_type": "MODIFY",
"old_path": "docker/config.env",
"new_path": "docker/config.env",
"diff": "@@ -14,10 +14,10 @@ MQTT_HOST=mqtt\nMQTT_PORT=1883\nMQTT_LISTENER_TOPIC=dev/#\n-MQTT_DEV_BINARY_SENSOR_INTERVAL=30\n+MQTT_DEV_BINARY_SENSOR_INTERVAL=60\nMQTT_DEV_BINARY_SENSOR_TOPIC=dev/mqtt-dev-binary-sensor/state\n-MQTT_DEV_SENSOR_INTERVAL=10\n+MQTT_DEV_SENSOR_INTERVAL=30\nMQTT_DEV_SENSOR_TOPIC=dev/mqtt-dev-sensor/state\nNODE_RED_URL=http://localhost:1880\n"
},
{
"change_type": "MODIFY",
"old_path": "docker/docker-compose.yml",
"new_path": "docker/docker-compose.yml",
"diff": "@@ -43,6 +43,7 @@ services:\ncommand: npm run dev:watch\nvolumes:\n- '..:/data-dev/node_modules/node-red-contrib-home-assistant'\n+ - './node-red/root-fs/data-dev/flows.json:/data-dev/flows.json' # Map flows file for easy commitable examples building\nports:\n- 1880:1880\n- 9123:9229\n@@ -53,8 +54,8 @@ services:\nbuild:\ncontext: ./home-assistant\n# While messing with HA config map the repo config to the container for easy changes\n- # volumes:\n- # - './home-assistant/root-fs/config/configuration.yaml:/config/configuration.yaml'\n+ volumes:\n+ - './home-assistant/root-fs/config/configuration.yaml:/config/configuration.yaml'\nports:\n- 8300:8300\n- 8123:8123\n"
},
{
"change_type": "MODIFY",
"old_path": "docker/home-assistant/root-fs/config/configuration.yaml",
"new_path": "docker/home-assistant/root-fs/config/configuration.yaml",
"diff": "@@ -51,9 +51,10 @@ panel_iframe:\n# Example configuration.yml entry\nswitch:\n- platform: mqtt\n- name: MQTT Switch\n- command_topic: dev/mqtt-switch/cmd\n- state_topic: dev/mqtt-switch/state\n+ name: MQTT Dev Switch\n+ command_topic: dev/mqtt-dev-switch/cmd\n+ state_topic: dev/mqtt-dev-switch/state\n+ opto\nsensor:\n- platform: mqtt\n"
},
{
"change_type": "MODIFY",
"old_path": "docker/node-red/root-fs/data-dev/flows.json",
"new_path": "docker/node-red/root-fs/data-dev/flows.json",
"diff": "\"type\": \"tab\",\n\"label\": \"Simple Test\"\n},\n+ {\n+ \"id\": \"ac309840.633668\",\n+ \"type\": \"tab\",\n+ \"label\": \"Current State\",\n+ \"disabled\": false,\n+ \"info\": \"\"\n+ },\n+ {\n+ \"id\": \"a9b7da37.df64a8\",\n+ \"type\": \"tab\",\n+ \"label\": \"All Nodes\",\n+ \"disabled\": false,\n+ \"info\": \"\"\n+ },\n{\n\"id\": \"aedb3267.4ec5f8\",\n\"type\": \"server\",\n\"71f7b01d.b0b6b\"\n]\n]\n+ },\n+ {\n+ \"id\": \"a450a11.4bb41e\",\n+ \"type\": \"inject\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"Inject entity_id\",\n+ \"topic\": \"\",\n+ \"payload\": \"{\\\"entity_id\\\":\\\"binary_sensor.mqtt_dev_binary_sensor\\\"}\",\n+ \"payloadType\": \"json\",\n+ \"repeat\": \"\",\n+ \"crontab\": \"\",\n+ \"once\": false,\n+ \"x\": 150,\n+ \"y\": 220,\n+ \"wires\": [\n+ [\n+ \"1ab59da9.008bf2\"\n+ ]\n+ ]\n+ },\n+ {\n+ \"id\": \"1b506d57.f6bdeb\",\n+ \"type\": \"server-events\",\n+ \"z\": \"a9b7da37.df64a8\",\n+ \"name\": \"Events: All\",\n+ \"server\": \"aedb3267.4ec5f8\",\n+ \"x\": 95,\n+ \"y\": 45,\n+ \"wires\": [\n+ [\n+ \"cfe34d00.3f0af8\"\n+ ]\n+ ]\n+ },\n+ {\n+ \"id\": \"49e83647.76b448\",\n+ \"type\": \"server-state-changed\",\n+ \"z\": \"a9b7da37.df64a8\",\n+ \"name\": \"Events: State Changed\",\n+ \"server\": \"aedb3267.4ec5f8\",\n+ \"entityidfilter\": \"binary_sensor.mqtt_dev_binary_sensor\",\n+ \"haltifstate\": \"\",\n+ \"x\": 135,\n+ \"y\": 95,\n+ \"wires\": [\n+ [\n+ \"3f8cfe6a.408b6a\"\n+ ]\n+ ]\n+ },\n+ {\n+ \"id\": \"949e61e9.cd005\",\n+ \"type\": \"api-current-state\",\n+ \"z\": \"a9b7da37.df64a8\",\n+ \"name\": \"Current State\",\n+ \"server\": \"aedb3267.4ec5f8\",\n+ \"halt_if\": \"\",\n+ \"entity_id\": \"binary_sensor.mqtt_dev_binary_sensor\",\n+ \"x\": 355,\n+ \"y\": 160,\n+ \"wires\": [\n+ [\n+ \"2aa47700.30b86a\"\n+ ]\n+ ]\n+ },\n+ {\n+ \"id\": \"70716f8b.302608\",\n+ \"type\": \"inject\",\n+ \"z\": \"a9b7da37.df64a8\",\n+ \"name\": \"\",\n+ \"topic\": \"\",\n+ \"payload\": \"\",\n+ \"payloadType\": \"date\",\n+ \"repeat\": \"\",\n+ \"crontab\": \"\",\n+ \"once\": false,\n+ \"x\": 115,\n+ \"y\": 160,\n+ \"wires\": [\n+ [\n+ \"949e61e9.cd005\",\n+ \"1236c799.f6e78\",\n+ \"640855fc.4c2c9c\"\n+ ]\n+ ]\n+ },\n+ {\n+ \"id\": \"1236c799.f6e78\",\n+ \"type\": \"api-render-template\",\n+ \"z\": \"a9b7da37.df64a8\",\n+ \"name\": \"Get Template\",\n+ \"server\": \"aedb3267.4ec5f8\",\n+ \"template\": \"{% for state in states.sensor %}\\n {{ state.entity_id }}={{ state.state }},\\n{% endfor %}\",\n+ \"x\": 365,\n+ \"y\": 255,\n+ \"wires\": [\n+ [\n+ \"b5c0827d.077f28\"\n+ ]\n+ ]\n+ },\n+ {\n+ \"id\": \"2aa47700.30b86a\",\n+ \"type\": \"debug\",\n+ \"z\": \"a9b7da37.df64a8\",\n+ \"name\": \"\",\n+ \"active\": false,\n+ \"console\": \"false\",\n+ \"complete\": \"true\",\n+ \"x\": 545,\n+ \"y\": 160,\n+ \"wires\": []\n+ },\n+ {\n+ \"id\": \"64ea9766.90aa5\",\n+ \"type\": \"debug\",\n+ \"z\": \"a9b7da37.df64a8\",\n+ \"name\": \"\",\n+ \"active\": true,\n+ \"console\": \"false\",\n+ \"complete\": \"true\",\n+ \"x\": 550,\n+ \"y\": 225,\n+ \"wires\": []\n+ },\n+ {\n+ \"id\": \"b5c0827d.077f28\",\n+ \"type\": \"debug\",\n+ \"z\": \"a9b7da37.df64a8\",\n+ \"name\": \"\",\n+ \"active\": false,\n+ \"console\": \"false\",\n+ \"complete\": \"true\",\n+ \"x\": 550,\n+ \"y\": 275,\n+ \"wires\": []\n+ },\n+ {\n+ \"id\": \"3f8cfe6a.408b6a\",\n+ \"type\": \"debug\",\n+ \"z\": \"a9b7da37.df64a8\",\n+ \"name\": \"\",\n+ \"active\": true,\n+ \"console\": \"false\",\n+ \"complete\": \"true\",\n+ \"x\": 335,\n+ \"y\": 95,\n+ \"wires\": []\n+ },\n+ {\n+ \"id\": \"cfe34d00.3f0af8\",\n+ \"type\": \"debug\",\n+ \"z\": \"a9b7da37.df64a8\",\n+ \"name\": \"\",\n+ \"active\": false,\n+ \"console\": \"false\",\n+ \"complete\": \"true\",\n+ \"x\": 335,\n+ \"y\": 45,\n+ \"wires\": []\n+ },\n+ {\n+ \"id\": \"640855fc.4c2c9c\",\n+ \"type\": \"api-get-history\",\n+ \"z\": \"a9b7da37.df64a8\",\n+ \"name\": \"\",\n+ \"server\": \"aedb3267.4ec5f8\",\n+ \"startdate\": \"\",\n+ \"x\": 360,\n+ \"y\": 210,\n+ \"wires\": [\n+ [\n+ \"64ea9766.90aa5\"\n+ ]\n+ ]\n+ },\n+ {\n+ \"id\": \"1ab59da9.008bf2\",\n+ \"type\": \"api-current-state\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"\",\n+ \"server\": \"aedb3267.4ec5f8\",\n+ \"halt_if\": \"\",\n+ \"entity_id\": \"sensor.mqtt_dev_sensor\",\n+ \"x\": 415,\n+ \"y\": 220,\n+ \"wires\": [\n+ [\n+ \"64fe8cc3.21d444\"\n+ ]\n+ ]\n+ },\n+ {\n+ \"id\": \"64fe8cc3.21d444\",\n+ \"type\": \"debug\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"\",\n+ \"active\": true,\n+ \"console\": \"false\",\n+ \"complete\": \"true\",\n+ \"x\": 645,\n+ \"y\": 220,\n+ \"wires\": []\n+ },\n+ {\n+ \"id\": \"44129cae.5bab0c\",\n+ \"type\": \"api-current-state\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"\",\n+ \"server\": \"aedb3267.4ec5f8\",\n+ \"halt_if\": \"\",\n+ \"entity_id\": \"sensor.mqtt_dev_sensor\",\n+ \"x\": 370,\n+ \"y\": 100,\n+ \"wires\": [\n+ [\n+ \"e3a5a997.d75e4\"\n+ ]\n+ ]\n+ },\n+ {\n+ \"id\": \"d4f47b6c.ad4fa\",\n+ \"type\": \"inject\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"\",\n+ \"topic\": \"\",\n+ \"payload\": \"\",\n+ \"payloadType\": \"date\",\n+ \"repeat\": \"\",\n+ \"crontab\": \"\",\n+ \"once\": false,\n+ \"x\": 140,\n+ \"y\": 100,\n+ \"wires\": [\n+ [\n+ \"44129cae.5bab0c\"\n+ ]\n+ ]\n+ },\n+ {\n+ \"id\": \"e3a5a997.d75e4\",\n+ \"type\": \"debug\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"\",\n+ \"active\": true,\n+ \"console\": \"false\",\n+ \"complete\": \"true\",\n+ \"x\": 650,\n+ \"y\": 100,\n+ \"wires\": []\n+ },\n+ {\n+ \"id\": \"8a2c0f6b.ead54\",\n+ \"type\": \"comment\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"Basic fetching of current state\",\n+ \"info\": \"\",\n+ \"x\": 150,\n+ \"y\": 50,\n+ \"wires\": []\n+ },\n+ {\n+ \"id\": \"c6f358bf.ee154\",\n+ \"type\": \"comment\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"Override the current state node's pre-configured entity_id value\",\n+ \"info\": \"\",\n+ \"x\": 260,\n+ \"y\": 170,\n+ \"wires\": []\n+ },\n+ {\n+ \"id\": \"7c6eac6c.6fdba4\",\n+ \"type\": \"inject\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"\",\n+ \"topic\": \"\",\n+ \"payload\": \"\",\n+ \"payloadType\": \"date\",\n+ \"repeat\": \"\",\n+ \"crontab\": \"\",\n+ \"once\": false,\n+ \"x\": 140,\n+ \"y\": 350,\n+ \"wires\": [\n+ [\n+ \"b3481b2.bb19068\"\n+ ]\n+ ]\n+ },\n+ {\n+ \"id\": \"b3481b2.bb19068\",\n+ \"type\": \"api-call-service\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"Set MQTT Binary sensor to off state\",\n+ \"server\": \"aedb3267.4ec5f8\",\n+ \"service_domain\": \"mqtt\",\n+ \"service\": \"publish\",\n+ \"data\": \"{\\\"topic\\\":\\\"dev/mqtt-dev-binary-sensor/state\\\",\\\"payload\\\":\\\"0\\\"}\",\n+ \"x\": 540,\n+ \"y\": 350,\n+ \"wires\": []\n+ },\n+ {\n+ \"id\": \"c3f15720.5a901\",\n+ \"type\": \"api-current-state\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"Get MQTT Binary Sensor state, halt if off\",\n+ \"server\": \"aedb3267.4ec5f8\",\n+ \"halt_if\": \"off\",\n+ \"entity_id\": \"binary_sensor.mqtt_dev_binary_sensor\",\n+ \"x\": 420,\n+ \"y\": 520,\n+ \"wires\": [\n+ [\n+ \"7f3c9194.2bc928\"\n+ ]\n+ ]\n+ },\n+ {\n+ \"id\": \"c5bbfd9e.fdb5\",\n+ \"type\": \"inject\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"\",\n+ \"topic\": \"\",\n+ \"payload\": \"\",\n+ \"payloadType\": \"date\",\n+ \"repeat\": \"\",\n+ \"crontab\": \"\",\n+ \"once\": false,\n+ \"x\": 140,\n+ \"y\": 520,\n+ \"wires\": [\n+ [\n+ \"c3f15720.5a901\"\n+ ]\n+ ]\n+ },\n+ {\n+ \"id\": \"7855b2b8.0d1334\",\n+ \"type\": \"comment\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"Override the current state node's pre-configured entity_id value\",\n+ \"info\": \"\",\n+ \"x\": 265,\n+ \"y\": 300,\n+ \"wires\": []\n+ },\n+ {\n+ \"id\": \"4c8253e2.d560cc\",\n+ \"type\": \"inject\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"Overide service data to turn on\",\n+ \"topic\": \"\",\n+ \"payload\": \"{\\\"data\\\":{\\\"topic\\\":\\\"dev/mqtt-dev-binary-sensor/state\\\",\\\"payload\\\":\\\"1\\\"}}\",\n+ \"payloadType\": \"json\",\n+ \"repeat\": \"\",\n+ \"crontab\": \"\",\n+ \"once\": false,\n+ \"x\": 210,\n+ \"y\": 390,\n+ \"wires\": [\n+ [\n+ \"b3481b2.bb19068\"\n+ ]\n+ ]\n+ },\n+ {\n+ \"id\": \"7f3c9194.2bc928\",\n+ \"type\": \"debug\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"\",\n+ \"active\": true,\n+ \"console\": \"false\",\n+ \"complete\": \"true\",\n+ \"x\": 670,\n+ \"y\": 520,\n+ \"wires\": []\n+ },\n+ {\n+ \"id\": \"73e5fa98.c017fc\",\n+ \"type\": \"server-state-changed\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"MQTT Binary Sensor State\",\n+ \"server\": \"aedb3267.4ec5f8\",\n+ \"entityidfilter\": \"binary_sensor.mqtt_dev_binary_sensor\",\n+ \"haltifstate\": \"\",\n+ \"x\": 500,\n+ \"y\": 410,\n+ \"wires\": [\n+ [\n+ \"306d8a57.83dd16\"\n+ ]\n+ ]\n+ },\n+ {\n+ \"id\": \"306d8a57.83dd16\",\n+ \"type\": \"function\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"Display State\",\n+ \"func\": \"const isOn = msg.payload === 'on';\\n\\nnode.status({ \\n fill: isOn ? 'green' : 'grey', \\n shape: isOn ? 'dot' : 'ring',\\n text: `Sensor is currently ${msg.payload}`\\n});\\nreturn msg;\",\n+ \"outputs\": 1,\n+ \"noerr\": 0,\n+ \"x\": 760,\n+ \"y\": 410,\n+ \"wires\": [\n+ []\n+ ]\n+ },\n+ {\n+ \"id\": \"685db7.9310f248\",\n+ \"type\": \"comment\",\n+ \"z\": \"ac309840.633668\",\n+ \"name\": \"Use above to test the Halt If option\",\n+ \"info\": \"\",\n+ \"x\": 180,\n+ \"y\": 470,\n+ \"wires\": []\n}\n]\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "node-api_current-state/node-api_current-state.html",
"new_path": "node-api_current-state/node-api_current-state.html",
"diff": "halt_if: { value: '' },\nentity_id: {\nvalue: '',\n- required: true,\n- validate: function (v) {\n- // TODO: On page load, if already configured with invalid entry it will not be\n- // picked up as invalid due to async load of this.availableEntities.\n- if (this.availableEntities) { return (this.availableEntities.indexOf(v) >= 0) };\n- return true;\n- }\n+ required: true\n}\n},\noneditprepare: function () {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Added examples of the current state node to the dev environment in docker node-red |
748,240 | 28.01.2018 16:26:52 | 18,000 | 0a2ce07d62a183bea7a60a573b64d74be8de247c | Improve error handling for api call by logging url, status and message in the node-red ui as well as console on server | [
{
"change_type": "MODIFY",
"old_path": "node-api_get-history/node-api_get-history.js",
"new_path": "node-api_get-history/node-api_get-history.js",
"diff": "@@ -21,7 +21,15 @@ const _int = {\nmsg.payload = res;\nnode.send(msg);\n})\n- .catch(err => node.error('Error calling service, home assistant api error', msg));\n+ .catch(err => {\n+ console.log(err);\n+ let notifyError = 'Error calling service, home assistant api error'\n+ notifyError = (err && err.response)\n+ ? notifyError += `: URL: ${err.response.config.url}, Status: ${err.response.status}, Message: ${err.message}`\n+ : notifyError += `: ${err.message}`;\n+\n+ node.error(notifyError, msg);\n+ });\n}\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Improve error handling for api call by logging url, status and message in the node-red ui as well as console on server |
748,240 | 29.01.2018 01:11:47 | 18,000 | 9d4063b9a34a96ea5368998388547160d727840a | Added tip for getting html syntax highlighting to work in VSCode for scripts | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -59,11 +59,6 @@ b. _Note: Also first run load of HomeAssistant web interface seems very slow, bu\n| mqtt-dev-binary-sensor | | publishes every 30 seconds to a topic home assistant has a `binary_sensor` for |\n-\n-\n-\n-\n-\n### Node Debugger via VSCode\nOptional but it's pretty nice if you have VSCode installed.\n- Open the project directory in VSCode\n@@ -72,3 +67,14 @@ Optional but it's pretty nice if you have VSCode installed.\n- Open [http://localhost:8123](http://localhost:8123) for HomeAssistant (password is `password` by default). There is a default config which includes mqtt with a couple mqtt sensors that autopublish every 10 and 30 seconds by default. MQTT broker is also launched via docker, checkout the `docker` dir for more details if interested.\n- For node-red either open up via the HomeAssistant web link or left hand menu or just open a browser tab to [http://localhost:1880](http://localhost:1880)\n+### Other Dev Tips\n+* If you're using VSCode and annoyed that node-red html ( `type=\"x-red\"` ) isn't syntax highlighted you can run force it by adding support. Below is for Mac, can do the same manually on any platform however, note that this is a hack as I couldn't find any other good way to do this.\n+\n+```shell\n+# For VSCode\n+sed -i .orig 's/text\\/(javascript|ecmascript|babel)/text\\/(javascript|ecmascript|babel|x-red)/' \"/Applications/Visual Studio Code.app/Contents/Resources/app/extensions/html/syntaxes/html.json\"\n+\n+# For VSCode Insiders\n+sed -i .orig 's/text\\/(javascript|ecmascript|babel)/text\\/(javascript|ecmascript|babel|x-red)/' \"/Applications/Visual Studio Code - Insiders.app/Contents/Resources/app/extensions/html/syntaxes/html.json\"\n+```\n+\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Added tip for getting html syntax highlighting to work in VSCode for scripts |
748,240 | 30.01.2018 16:25:49 | 18,000 | b058b5b6ae62a7a164cf8f8d771da9ce56173386 | Docker-compose do not map root-fs volumes | [
{
"change_type": "MODIFY",
"old_path": "docker/docker-compose.yml",
"new_path": "docker/docker-compose.yml",
"diff": "@@ -43,7 +43,7 @@ services:\ncommand: npm run dev:watch\nvolumes:\n- '..:/data-dev/node_modules/node-red-contrib-home-assistant'\n- - './node-red/root-fs/data-dev/flows.json:/data-dev/flows.json' # Map flows file for easy commitable examples building\n+ # - './node-red/root-fs/data-dev/flows.json:/data-dev/flows.json' # Map flows file for easy commitable examples building\nports:\n- 1880:1880\n- 9123:9229\n@@ -55,7 +55,7 @@ services:\ncontext: ./home-assistant\n# While messing with HA config map the repo config to the container for easy changes\nvolumes:\n- - './home-assistant/root-fs/config/configuration.yaml:/config/configuration.yaml'\n+ # - './home-assistant/root-fs/config/configuration.yaml:/config/configuration.yaml'\nports:\n- 8300:8300\n- 8123:8123\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Docker-compose do not map root-fs volumes |
748,240 | 30.01.2018 16:27:50 | 18,000 | 783b6994662894695ca3299d2a9804c9ee82bfb8 | adding settings.js for node-red, was gitignored | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "docker/node-red/root-fs/data-dev/settings.js",
"diff": "+module.exports = {\n+ uiPort: process.env.PORT || 1880,\n+ mqttReconnectTime: 15000,\n+ serialReconnectTime: 15000,\n+ debugMaxLength: 1000,\n+ debugUseColors: true,\n+ flowFilePretty: true,\n+\n+\n+ // context.global.os for example\n+ functionGlobalContext: { os: require('os') },\n+ paletteCategories: ['home_assistant', 'subflows', 'input', 'output', 'function', 'social', 'mobile', 'storage', 'analysis', 'advanced'],\n+ logging: {\n+ console: {\n+ level: 'debug',\n+ metrics: false,\n+ audit: false\n+ }\n+ }\n+}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | adding settings.js for node-red, was gitignored |
748,240 | 30.01.2018 22:08:31 | 18,000 | ff2b2becd0134721d8db2b2baab420d27d3a911d | refactor node-red docker, using custom node docker image to upgrade to node 8LTS (min requirement now) | [
{
"change_type": "MODIFY",
"old_path": "_docker/docker-compose.yml",
"new_path": "_docker/docker-compose.yml",
"diff": "@@ -42,7 +42,7 @@ services:\ncontext: ./node-red\ncommand: npm run dev:watch\nvolumes:\n- - '..:/data-dev/node_modules/node-red-contrib-home-assistant'\n+ - '..:/data/node_modules/node-red-contrib-home-assistant'\n# - './node-red/root-fs/data-dev/flows.json:/data-dev/flows.json' # Map flows file for easy commitable examples building\nports:\n- 1880:1880\n"
},
{
"change_type": "MODIFY",
"old_path": "_docker/node-red/Dockerfile",
"new_path": "_docker/node-red/Dockerfile",
"diff": "-FROM nodered/node-red-docker:0.17.5-slim\n+FROM node:8.9.4\n-# RUN npm install node-red-contrib-home-assistant\n-\n-# Node Red image marks /data as volume so copy doesn't work there\nCOPY root-fs /\n-COPY root-fs/data-dev/settings.js /data-dev/settings.js\n+RUN chown -R node:node /data /app\n+\n+# Install NodeRed base app\n+ENV HOME=/app\n+USER node\n+WORKDIR /app\n+RUN npm install\n+\n+# Install Useful Home Automation Nodes\n+RUN npm install \\\n+ node-red-contrib-bigstatus\n+\n+# User configuration directory volume\n+EXPOSE 1880\n+EXPOSE 9229\n-USER root\n-RUN chown -R node-red:node-red /data-dev\n-RUN npm install --global nodemon\n-USER node-red\n+# Environment variable holding file path for flows configuration\n+ENV USER_DIR=/data\n+ENV FLOWS=flows.json\n+ENV NODE_PATH=/app/node_modules:/data/node_modules\n+ENV NODEMON_CONFIG=/app/nodemon.json\n-WORKDIR /data-dev\n-CMD [\"node\", \"/usr/src/node-red/node_modules/node-red/red.js\", \"--userDir\", \"/data-dev\", \"-v\", \"flows.json\"]\n+CMD [\"npm\", \"start\"]\n"
},
{
"change_type": "RENAME",
"old_path": "_docker/node-red/root-fs/data-dev/nodemon.json",
"new_path": "_docker/node-red/root-fs/app/nodemon.json",
"diff": "{\n\"colours\": true,\n\"delay\": 1,\n- \"ignore\": [\n- \"/data-dev/node_modules/node-red-contrib-home-assistant/docker/**/*\",\n- \"/data-dev/node_modules/node-red-contrib-home-assistant/node_modules/**/*\"\n- ],\n\"verbose\": false,\n\"watch\": [\n- \"/data-dev/node_modules/node-red-contrib-home-assistant\"\n+ \"/data/node_modules/node-red-contrib-home-assistant\"\n],\n\"env\": {\n\"NODE_ENV\": \"development\"\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "_docker/node-red/root-fs/app/package.json",
"diff": "+{\n+ \"name\": \"node-red-contrib-home-assistant-docker\",\n+ \"version\": \"1.0.0\",\n+ \"description\": \"Node red install for docker, tailored for use with Home Assistant\",\n+ \"homepage\": \"https://github.com/ayapejian/node-red-contrib-home-assistant\",\n+ \"main\": \"node_modules/node-red/red/red.js\",\n+ \"scripts\": {\n+ \"start\": \"node $NODE_OPTIONS /app/node_modules/node-red/red.js -v --userDir $USER_DIR $FLOWS\",\n+ \"dev:watch\": \"/app/node_modules/.bin/nodemon --inspect=0.0.0.0:9229 --config $NODEMON_CONFIG /app/node_modules/node-red/red.js -- -v --userDir $USER_DIR $FLOWS\"\n+ },\n+ \"dependencies\": {\n+ \"node-red\": \"0.17.5\",\n+ \"nodemon\": \"1.14.11\"\n+ },\n+ \"engines\": {\n+ \"node\": \"8.*.*\"\n+ }\n+}\n"
},
{
"change_type": "DELETE",
"old_path": "_docker/node-red/root-fs/data-dev/flows_cred.json",
"new_path": null,
"diff": "-{\n- \"$\": \"ed13f5ce1158988bbbc085b8721fb6e9Tws=\"\n-}\n\\ No newline at end of file\n"
},
{
"change_type": "RENAME",
"old_path": "_docker/node-red/root-fs/data-dev/flows.json",
"new_path": "_docker/node-red/root-fs/data/flows.json",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "_docker/node-red/root-fs/data-dev/package.json",
"new_path": "_docker/node-red/root-fs/data/package.json",
"diff": ""
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | refactor node-red docker, using custom node docker image to upgrade to node 8LTS (min requirement now) |
748,240 | 31.01.2018 14:35:29 | 18,000 | 02391f80b5bae7eacb4a5ef76fd6a3492a949e42 | Added BaseNode class, current state node converted to use that class | [
{
"change_type": "MODIFY",
"old_path": ".vscode/launch.json",
"new_path": ".vscode/launch.json",
"diff": "\"address\": \"localhost\",\n\"port\": 9123,\n\"localRoot\": \"${workspaceFolder}\",\n- \"remoteRoot\": \"/data-dev/node_modules/node-red-contrib-home-assistant\",\n+ \"remoteRoot\": \"/data/node_modules/node-red-contrib-home-assistant\",\n\"trace\": false,\n\"skipFiles\": [\n\"<node_internals>/**/*.js\"\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "lib/base-node.js",
"diff": "+const Joi = require('joi');\n+const merge = require('lodash.merge');\n+const selectn = require('selectn');\n+\n+const _internals = {\n+ parseInputMessage(inputOptions, msg) {\n+ if (!inputOptions) return;\n+ let parsedResult = {};\n+\n+ for (let [fieldKey, fieldConfig] of Object.entries(inputOptions)) {\n+ // Try to load from message\n+ let result = { key: fieldKey, value: selectn(fieldConfig.messageProp, msg), source: 'message', validation: null };\n+\n+ // If message missing value and node has config that can be used instead\n+ if (result.value === undefined && fieldConfig.configProp) {\n+ result.value = selectn(fieldConfig.configProp, this.nodeConfig);\n+ result.source = 'config';\n+ }\n+\n+ // If value not found in both config and message\n+ if (result.value === undefined) {\n+ result.source = 'missing';\n+ }\n+\n+ // If validation for value is configured run validation, optionally throwing on failed validation\n+ if (fieldConfig.validation) {\n+ const { error, value } = Joi.validate(result.value, fieldConfig.validation.schema, { convert: true });\n+ if (error && fieldConfig.validation.haltOnFail) throw error;\n+ result.validation = { error, value };\n+ }\n+\n+ // Assign result to config key value\n+ parsedResult[fieldKey] = result;\n+ }\n+\n+ return parsedResult;\n+ }\n+};\n+\n+const _eventHandlers = {\n+ preOnInput(message) {\n+ this.debug('Incoming message: ', message);\n+ if (this.options.debug) this.flashStatus();\n+ try {\n+ const parsedMessage = _internals.parseInputMessage.call(this, this.options.input, message);\n+\n+ this.onInput({\n+ parsedMessage,\n+ message\n+ });\n+ } catch (e) {\n+ if (e && e.isJoi) {\n+ this.setStatusError('Validation Error, flow halted');\n+ this.node.warn(e.message);\n+ return this.send(null);\n+ }\n+ throw e;\n+ }\n+ },\n+ async preOnClose(removed, done) {\n+ if (removed) {\n+ this.debug('Closing node. Reason: Deleted');\n+ } else {\n+ this.debug('Closing node. Reason: Restarted');\n+ }\n+ await this.onClose(removed);\n+ // Clear previous status messages\n+ this.setStatus();\n+ done();\n+ }\n+};\n+\n+const DEFAULT_OPTIONS = {\n+ debug: false,\n+ config: {},\n+ input: {\n+ topic: { messageProp: 'topic' },\n+ payload: { messageProp: 'payload' }\n+ }\n+};\n+\n+class BaseNode {\n+ constructor(nodeDefinition, RED, options = {}) {\n+ // Need to bring in NodeRed dependency and properly extend Node class, or just make this class a node handler\n+ RED.nodes.createNode(this, nodeDefinition);\n+ this.node = this;\n+\n+ this.RED = RED;\n+ this.options = merge({}, DEFAULT_OPTIONS, options);\n+ this._eventHandlers = _eventHandlers;\n+ this._internals = _internals;\n+\n+ this.nodeConfig = Object.entries(this.options.config).reduce((acc, [key, config]) => {\n+ acc[key] = config.isNode ? this.RED.nodes.getNode(nodeDefinition[key]) : nodeDefinition[key];\n+ return acc;\n+ }, {});\n+\n+ this.node.on('input', this._eventHandlers.preOnInput.bind(this));\n+ this.node.on('close', this._eventHandlers.preOnClose.bind(this));\n+\n+ this.debug('Instantiated Node with node config and basenode options: ', this.nodeConfig, this.options);\n+ }\n+\n+ // Subclasses should override these as hooks into common events\n+ onClose(removed) {}\n+ onInput() {}\n+\n+ send() { this.node.send(...arguments) }\n+\n+ flashFlowHaltedStatus() {\n+ this.flashStatus({\n+ statusFlash: { fill: 'yellow', shape: 'dot' },\n+ statusAfter: { fill: 'yellow', shape: 'dot', text: `${new Date().toISOString()}: Node halted flow` },\n+ clearAfter: 5000\n+ });\n+ }\n+\n+ flashStatus(flashOptions = {}) {\n+ const flashOpts = Object.assign({}, { statusFlash: null, statusAfter: {}, clearAfter: 0 }, flashOptions);\n+ this.statusClear();\n+\n+ let hide = () => this.node.status({});\n+ let show = (status) => this.node.status(status || { shape: 'dot', fill: 'grey' });\n+\n+ let showing = false;\n+ this.timersStatusFlash = setInterval(() => {\n+ (showing) ? hide() : show(flashOpts.statusFlash);\n+ showing = !showing;\n+ }, 100);\n+\n+ this.timersStatusFlashStop = setTimeout(() => {\n+ clearInterval(this.timersStatusFlash);\n+ show(flashOpts.statusAfter);\n+ this.timersStatusClear = setTimeout(() => hide(), flashOpts.clearAfter);\n+ }, 1000);\n+ };\n+\n+ // Cancel any timers associated with and blank out the status\n+ statusClear() {\n+ clearInterval(this.timersStatusFlash);\n+ clearTimeout(this.timersStatusFlashStop);\n+ clearTimeout(this.timersStatusClear);\n+ this.node.status({});\n+ }\n+\n+ setStatusError(msg) {\n+ this.setStatus({ fill: 'red', shape: 'ring', text: msg });\n+ }\n+\n+ setStatus(opts = { shape: 'dot', fill: 'blue', text: '' }) {\n+ this.node.status(opts);\n+ }\n+\n+ debug() {\n+ if (!this.options.debug) return;\n+ console.log(`*****DEBUG: ${this.node.type}:${this.node.id}`, ...arguments);\n+ }\n+}\n+\n+module.exports = BaseNode;\n"
},
{
"change_type": "RENAME",
"old_path": "nodes/api_current-state/node-api_current-state.html",
"new_path": "nodes/api_current-state/api_current-state.html",
"diff": ""
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "nodes/api_current-state/api_current-state.js",
"diff": "+const BaseNode = require('../../lib/base-node');\n+const Joi = require('joi');\n+\n+module.exports = function(RED) {\n+ const nodeOptions = {\n+ debug: true,\n+ config: {\n+ name: {},\n+ halt_if: {},\n+ entity_id: {},\n+ server: { isNode: true }\n+ },\n+ input: {\n+ entity_id: {\n+ messageProp: 'payload.entity_id',\n+ configProp: 'entity_id', // Will be used if value not found on message,\n+ validation: {\n+ haltOnFail: true,\n+ schema: Joi.string() // Validates on message if exists, Joi will also attempt coercion\n+ }\n+ }\n+ }\n+ };\n+\n+ class CurrentState extends BaseNode {\n+ constructor(nodeDefinition) {\n+ super(nodeDefinition, RED, nodeOptions);\n+ }\n+\n+ onInput({ parsedMessage, message }) {\n+ const entity_id = parsedMessage.entity_id.value;\n+ const logAndContinueEmpty = (logMsg) => { this.node.warn(logMsg); return ({ payload: {}}) };\n+\n+ if (!entity_id) return logAndContinueEmpty('entity ID not set, cannot get current state, sending empty payload');\n+\n+ const { states } = this.nodeConfig.server.homeAssistant;\n+ if (!states) return logAndContinueEmpty('local state cache missing, sending empty payload');\n+\n+ const currentState = states[entity_id];\n+ if (!currentState) return logAndContinueEmpty(`entity could not be found in cache for entity_id: ${entity_id}, sending empty payload`);\n+\n+ const shouldHaltIfState = this.nodeConfig.halt_if && (currentState.state === this.nodeConfig.halt_if);\n+ if (shouldHaltIfState) {\n+ this.debug(`Get current state: halting processing due to current state of ${entity_id} matches \"halt if state\" option`);\n+ this.flashFlowHaltedStatus();\n+ return null;\n+ }\n+\n+ this.node.send({ topic: entity_id, payload: currentState.state, data: currentState });\n+ }\n+ }\n+\n+ RED.nodes.registerType('api-current-state', CurrentState);\n+};\n"
},
{
"change_type": "MODIFY",
"old_path": "package-lock.json",
"new_path": "package-lock.json",
"diff": "\"concat-map\": \"0.0.1\"\n}\n},\n+ \"brackets2dots\": {\n+ \"version\": \"1.1.0\",\n+ \"resolved\": \"https://registry.npmjs.org/brackets2dots/-/brackets2dots-1.1.0.tgz\",\n+ \"integrity\": \"sha1-Pz1AN1/GYM4P0AT6J9Z7NPlGmsM=\"\n+ },\n\"builtin-modules\": {\n\"version\": \"1.1.1\",\n\"resolved\": \"https://registry.npmjs.org/builtin-modules/-/builtin-modules-1.1.1.tgz\",\n\"integrity\": \"sha1-/xnt6Kml5XkyQUewwR8PvLq+1jk=\",\n\"dev\": true\n},\n+ \"clone-deep\": {\n+ \"version\": \"3.0.1\",\n+ \"resolved\": \"https://registry.npmjs.org/clone-deep/-/clone-deep-3.0.1.tgz\",\n+ \"integrity\": \"sha512-kWn5hGUnIA4algk62xJIp9jxQZ8DxSPg9ktkkK1WxRGhU/0GKZBekYJHXAXaZKMpxoq/7R4eygeIl9Cf7si+bA==\",\n+ \"requires\": {\n+ \"for-own\": \"1.0.0\",\n+ \"is-plain-object\": \"2.0.4\",\n+ \"kind-of\": \"6.0.2\",\n+ \"shallow-clone\": \"2.0.2\"\n+ }\n+ },\n\"co\": {\n\"version\": \"4.6.0\",\n\"resolved\": \"https://registry.npmjs.org/co/-/co-4.6.0.tgz\",\n\"which\": \"1.3.0\"\n}\n},\n+ \"curry2\": {\n+ \"version\": \"1.0.3\",\n+ \"resolved\": \"https://registry.npmjs.org/curry2/-/curry2-1.0.3.tgz\",\n+ \"integrity\": \"sha1-OBkdVfEGC/6kfKCACThbuHj2YS8=\",\n+ \"requires\": {\n+ \"fast-bind\": \"1.0.0\"\n+ }\n+ },\n\"date-fns\": {\n\"version\": \"1.28.5\",\n\"resolved\": \"https://registry.npmjs.org/date-fns/-/date-fns-1.28.5.tgz\",\n\"domelementtype\": \"1.3.0\"\n}\n},\n+ \"dotsplit.js\": {\n+ \"version\": \"1.1.0\",\n+ \"resolved\": \"https://registry.npmjs.org/dotsplit.js/-/dotsplit.js-1.1.0.tgz\",\n+ \"integrity\": \"sha1-JaI56r6SKpH/pdKhctbJ+4JFHgI=\"\n+ },\n\"emojis-list\": {\n\"version\": \"2.1.0\",\n\"resolved\": \"https://registry.npmjs.org/emojis-list/-/emojis-list-2.1.0.tgz\",\n\"tmp\": \"0.0.33\"\n}\n},\n+ \"fast-bind\": {\n+ \"version\": \"1.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/fast-bind/-/fast-bind-1.0.0.tgz\",\n+ \"integrity\": \"sha1-f6llLLMyX1zR4lLWy08WDeGnbnU=\"\n+ },\n\"fast-deep-equal\": {\n\"version\": \"1.0.0\",\n\"resolved\": \"https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-1.0.0.tgz\",\n\"debug\": \"2.6.8\"\n}\n},\n+ \"for-in\": {\n+ \"version\": \"1.0.2\",\n+ \"resolved\": \"https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz\",\n+ \"integrity\": \"sha1-gQaNKVqBQuwKxybG4iAMMPttXoA=\"\n+ },\n+ \"for-own\": {\n+ \"version\": \"1.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/for-own/-/for-own-1.0.0.tgz\",\n+ \"integrity\": \"sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs=\",\n+ \"requires\": {\n+ \"for-in\": \"1.0.2\"\n+ }\n+ },\n\"fs.realpath\": {\n\"version\": \"1.0.0\",\n\"resolved\": \"https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz\",\n\"integrity\": \"sha1-6CB68cx7MNRGzHC3NLXovhj4jVE=\",\n\"dev\": true\n},\n+ \"hoek\": {\n+ \"version\": \"5.0.2\",\n+ \"resolved\": \"https://registry.npmjs.org/hoek/-/hoek-5.0.2.tgz\",\n+ \"integrity\": \"sha512-NA10UYP9ufCtY2qYGkZktcQXwVyYK4zK0gkaFSB96xhtlo6V8tKXdQgx8eHolQTRemaW0uLn8BhjhwqrOU+QLQ==\"\n+ },\n\"hosted-git-info\": {\n\"version\": \"2.5.0\",\n\"resolved\": \"https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-2.5.0.tgz\",\n\"builtin-modules\": \"1.1.1\"\n}\n},\n+ \"is-extendable\": {\n+ \"version\": \"1.0.1\",\n+ \"resolved\": \"https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz\",\n+ \"integrity\": \"sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==\",\n+ \"requires\": {\n+ \"is-plain-object\": \"2.0.4\"\n+ }\n+ },\n\"is-fullwidth-code-point\": {\n\"version\": \"2.0.0\",\n\"resolved\": \"https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz\",\n\"path-is-inside\": \"1.0.2\"\n}\n},\n+ \"is-plain-object\": {\n+ \"version\": \"2.0.4\",\n+ \"resolved\": \"https://registry.npmjs.org/is-plain-object/-/is-plain-object-2.0.4.tgz\",\n+ \"integrity\": \"sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==\",\n+ \"requires\": {\n+ \"isobject\": \"3.0.1\"\n+ }\n+ },\n\"is-promise\": {\n\"version\": \"2.1.0\",\n\"resolved\": \"https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz\",\n\"integrity\": \"sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=\",\n\"dev\": true\n},\n+ \"isemail\": {\n+ \"version\": \"3.1.0\",\n+ \"resolved\": \"https://registry.npmjs.org/isemail/-/isemail-3.1.0.tgz\",\n+ \"integrity\": \"sha512-Ke15MBbbhyIhZzWheiWuRlTO81tTH4RQvrbJFpVzJce8oyVrCVSDdrcw4TcyMsaS/fMGJSbU3lTsqCGDKwrzww==\",\n+ \"requires\": {\n+ \"punycode\": \"2.1.0\"\n+ }\n+ },\n\"isexe\": {\n\"version\": \"2.0.0\",\n\"resolved\": \"https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz\",\n\"integrity\": \"sha1-6PvzdNxVb/iUehDcsFctYz8s+hA=\",\n\"dev\": true\n},\n+ \"isobject\": {\n+ \"version\": \"3.0.1\",\n+ \"resolved\": \"https://registry.npmjs.org/isobject/-/isobject-3.0.1.tgz\",\n+ \"integrity\": \"sha1-TkMekrEalzFjaqH5yNHMvP2reN8=\"\n+ },\n+ \"joi\": {\n+ \"version\": \"13.1.1\",\n+ \"resolved\": \"https://registry.npmjs.org/joi/-/joi-13.1.1.tgz\",\n+ \"integrity\": \"sha512-Y44bDwIoeCjFDRO18VaMRc0hIdPkLbZaF2VqU7t1tCcno3S3XzsmlYYpOu0Qk6nkzoI5RSao7W57NTvPKxbkcg==\",\n+ \"requires\": {\n+ \"hoek\": \"5.0.2\",\n+ \"isemail\": \"3.1.0\",\n+ \"topo\": \"3.0.0\"\n+ }\n+ },\n\"js-tokens\": {\n\"version\": \"3.0.2\",\n\"resolved\": \"https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz\",\n\"integrity\": \"sha1-Hq3nrMASA0rYTiOWdn6tn6VJWCE=\",\n\"dev\": true\n},\n+ \"kind-of\": {\n+ \"version\": \"6.0.2\",\n+ \"resolved\": \"https://registry.npmjs.org/kind-of/-/kind-of-6.0.2.tgz\",\n+ \"integrity\": \"sha512-s5kLOcnH0XqDO+FvuaLX8DDjZ18CGFk7VygH40QoKPUQhW4e2rvM0rwUq0t8IQDOwYSeLK01U90OjzBTme2QqA==\"\n+ },\n\"levn\": {\n\"version\": \"0.3.0\",\n\"resolved\": \"https://registry.npmjs.org/levn/-/levn-0.3.0.tgz\",\n\"integrity\": \"sha1-9HGh2khr5g9quVXRcRVSPdHSVdU=\",\n\"dev\": true\n},\n+ \"lodash.merge\": {\n+ \"version\": \"4.6.0\",\n+ \"resolved\": \"https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.0.tgz\",\n+ \"integrity\": \"sha1-aYhLoUSsM/5plzemCG3v+t0PicU=\"\n+ },\n\"lru-cache\": {\n\"version\": \"4.1.1\",\n\"resolved\": \"https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.1.tgz\",\n\"integrity\": \"sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=\",\n\"dev\": true\n},\n+ \"mixin-object\": {\n+ \"version\": \"3.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/mixin-object/-/mixin-object-3.0.0.tgz\",\n+ \"integrity\": \"sha512-RsUqTd3DyF9+UPqhLzJIWwGm4ZGIPYOu6WcQhQuBqqVBGhc6LOC8LrFk9KD7PvVwmqri45IJT88WLrNNrMWjxg==\",\n+ \"requires\": {\n+ \"for-in\": \"1.0.2\",\n+ \"is-extendable\": \"1.0.1\"\n+ }\n+ },\n\"mkdirp\": {\n\"version\": \"0.5.1\",\n\"resolved\": \"https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz\",\n\"integrity\": \"sha1-8FKijacOYYkX7wqKw0wa5aaChrM=\",\n\"dev\": true\n},\n+ \"punycode\": {\n+ \"version\": \"2.1.0\",\n+ \"resolved\": \"https://registry.npmjs.org/punycode/-/punycode-2.1.0.tgz\",\n+ \"integrity\": \"sha1-X4Y+3Im5bbCQdLrXlHvwkFbKTn0=\"\n+ },\n\"querystringify\": {\n\"version\": \"0.0.4\",\n\"resolved\": \"https://registry.npmjs.org/querystringify/-/querystringify-0.0.4.tgz\",\n\"integrity\": \"sha512-kKvNJn6Mm93gAczWVJg7wH+wGYWNrDHdWvpUmHyEsgCtIwwo3bqPtV4tR5tuPaUhTOo/kvhVwd8XwwOllGYkbg==\",\n\"dev\": true\n},\n+ \"selectn\": {\n+ \"version\": \"1.1.2\",\n+ \"resolved\": \"https://registry.npmjs.org/selectn/-/selectn-1.1.2.tgz\",\n+ \"integrity\": \"sha1-/IrNkd8/RaywGJHGdzrlKYUdaxc=\",\n+ \"requires\": {\n+ \"brackets2dots\": \"1.1.0\",\n+ \"curry2\": \"1.0.3\",\n+ \"debug\": \"2.6.8\",\n+ \"dotsplit.js\": \"1.1.0\"\n+ }\n+ },\n\"semver\": {\n\"version\": \"5.5.0\",\n\"resolved\": \"https://registry.npmjs.org/semver/-/semver-5.5.0.tgz\",\n\"integrity\": \"sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA==\",\n\"dev\": true\n},\n+ \"shallow-clone\": {\n+ \"version\": \"2.0.2\",\n+ \"resolved\": \"https://registry.npmjs.org/shallow-clone/-/shallow-clone-2.0.2.tgz\",\n+ \"integrity\": \"sha512-2o81AG/RpLTAG/ZXQekPtH/6yTffzKlJ+i6UhtVTtnP6zWQaNo9vt6LI28bhZLSesB12VQSfJYtXopTogVBveg==\",\n+ \"requires\": {\n+ \"is-extendable\": \"1.0.1\",\n+ \"kind-of\": \"6.0.2\",\n+ \"mixin-object\": \"3.0.0\"\n+ }\n+ },\n\"shebang-command\": {\n\"version\": \"1.2.0\",\n\"resolved\": \"https://registry.npmjs.org/shebang-command/-/shebang-command-1.2.0.tgz\",\n\"os-tmpdir\": \"1.0.2\"\n}\n},\n+ \"topo\": {\n+ \"version\": \"3.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/topo/-/topo-3.0.0.tgz\",\n+ \"integrity\": \"sha512-Tlu1fGlR90iCdIPURqPiufqAlCZYzLjHYVVbcFWDMcX7+tK8hdZWAfsMrD/pBul9jqHHwFjNdf1WaxA9vTRRhw==\",\n+ \"requires\": {\n+ \"hoek\": \"5.0.2\"\n+ }\n+ },\n\"type-check\": {\n\"version\": \"0.3.2\",\n\"resolved\": \"https://registry.npmjs.org/type-check/-/type-check-0.3.2.tgz\",\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"server-events\": \"nodes/server-events/node-server-events.js\",\n\"server-state-changed\": \"nodes/server-state-changed/node-server-state-changed.js\",\n\"api-call-service\": \"nodes/api_call-service/node-api_call-service.js\",\n- \"api-current-state\": \"nodes/api_current-state/node-api_current-state.js\",\n+ \"api-current-state\": \"nodes/api_current-state/api_current-state.js\",\n\"api-get-history\": \"nodes/api_get-history/node-api_get-history.js\",\n\"api-render-template\": \"nodes/api_render-template/node-api_render-template.js\"\n}\n},\n\"dependencies\": {\n+ \"clone-deep\": \"^3.0.1\",\n\"date-fns\": \"^1.28.5\",\n\"debug\": \"^2.6.3\",\n\"is-string\": \"^1.0.4\",\n- \"node-home-assistant\": \"0.1.0\"\n+ \"joi\": \"^13.1.1\",\n+ \"lodash.merge\": \"^4.6.0\",\n+ \"node-home-assistant\": \"0.1.0\",\n+ \"selectn\": \"^1.1.2\"\n},\n\"devDependencies\": {\n\"eslint\": \"^4.8.0\",\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Added BaseNode class, current state node converted to use that class |
748,240 | 01.02.2018 13:05:29 | 18,000 | cdaa9c00c2d54db1e0d0f527112d82694794268b | Centralized event based logic into base EventNode class | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "lib/events-node.js",
"diff": "+const merge = require('lodash.merge');\n+const BaseNode = require('./base-node');\n+\n+const DEFAULT_NODE_OPTIONS = {\n+ debug: false,\n+ config: {\n+ name: {},\n+ server: { isNode: true }\n+ }\n+};\n+\n+class EventsNode extends BaseNode {\n+ constructor(nodeDefinition, RED, nodeOptions = {}) {\n+ nodeOptions = merge({}, DEFAULT_NODE_OPTIONS, nodeOptions);\n+ super(nodeDefinition, RED, nodeOptions);\n+ this.listeners = {};\n+\n+ this.addEventClientListener({ event: 'ha_events:close', handler: this.onHaEventsClose.bind(this) });\n+ this.addEventClientListener({ event: 'ha_events:open', handler: this.onHaEventsOpen.bind(this) });\n+ this.addEventClientListener({ event: 'ha_events:error', handler: this.onHaEventsError.bind(this) });\n+\n+ this.setConnectionStatus(this.isConnected);\n+ }\n+\n+ addEventClientListener({ event, handler }) {\n+ this.listeners[event] = handler;\n+ this.eventsClient.addListener(event, handler);\n+ }\n+\n+ onClose(nodeRemoved) {\n+ if (this.eventsClient) {\n+ Object.entries(this.listeners).forEach(([event, handler]) => {\n+ this.eventsClient.removeListener(event, handler);\n+ });\n+ }\n+ }\n+\n+ onHaEventsClose() {\n+ this.setConnectionStatus(false);\n+ }\n+ onHaEventsOpen() {\n+ this.setConnectionStatus(true);\n+ }\n+\n+ onHaEventsError(err) {\n+ if (err.message) this.error(err.message);\n+ }\n+\n+ setConnectionStatus(isConnected) {\n+ (isConnected)\n+ ? this.setStatus({ shape: 'dot', fill: 'green', text: 'connected' })\n+ : this.setStatus({ shape: 'ring', fill: 'red', text: 'disconnected' });\n+ }\n+\n+ get eventsClient() {\n+ return this.reach('nodeConfig.server.events');\n+ }\n+\n+ get isConnected() {\n+ return this.eventsClient && this.eventsClient.connected;\n+ }\n+};\n+\n+module.exports = EventsNode;\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/server-events-all/server-events-all.js",
"new_path": "nodes/server-events-all/server-events-all.js",
"diff": "-const BaseNode = require('../../lib/base-node');\n+const EventsNode = require('../../lib/events-node');\nmodule.exports = function(RED) {\n- const nodeOptions = {\n- debug: true,\n- config: {\n- name: {},\n- server: { isNode: true }\n- }\n- };\n-\n- class ServerEventsNode extends BaseNode {\n+ class ServerEventsNode extends EventsNode {\nconstructor(nodeDefinition) {\n- super(nodeDefinition, RED, nodeOptions);\n-\n- this.listeners = {\n- onHaEventsAll: this.onHaEventsAll.bind(this),\n- onHaEventsClose: this.onHaEventsClose.bind(this),\n- onHaEventsOpen: this.onHaEventsOpen.bind(this),\n- onHaEventsError: this.onHaEventsError.bind(this)\n- };\n-\n- this.setConnectionStatus(this.isConnected);\n-\n- if (this.eventsClient) {\n- this.eventsClient.addListener('ha_events:all', this.listeners.onHaEventsAll);\n- this.eventsClient.addListener('ha_events:close', this.listeners.onHaEventsClose);\n- this.eventsClient.addListener('ha_events:open', this.listeners.onHaEventsOpen);\n- this.eventsClient.addListener('ha_events:error', this.listeners.onHaEventsError);\n- }\n- }\n-\n- onClose(nodeRemoved) {\n- if (this.eventsClient) {\n- this.eventsClient.removeListener('ha_events:all', this.listeners.onHaEventsAll);\n- this.eventsClient.removeListener('ha_events:close', this.listeners.onHaEventsClose);\n- this.eventsClient.removeListener('ha_events:open', this.listeners.onHaEventsOpen);\n- this.eventsClient.removeListener('ha_events:error', this.listeners.onHaEventsError);\n- }\n+ super(nodeDefinition, RED);\n+ this.addEventClientListener({ event: 'ha_events:all', handler: this.onHaEventsAll.bind(this) });\n}\nonHaEventsAll(evt) {\nthis.send({ event_type: evt.event_type, topic: evt.event_type, payload: evt });\nthis.flashStatus();\n}\n- onHaEventsClose() {\n- this.setConnectionStatus(false);\n- }\n- onHaEventsOpen() {\n- this.setConnectionStatus(true);\n- }\n-\n- onHaEventsError(err) {\n- if (err.message) this.error(err.message);\n- }\n-\n- setConnectionStatus(isConnected) {\n- (isConnected)\n- ? this.setStatus({ shape: 'dot', fill: 'green', text: 'connected' })\n- : this.setStatus({ shape: 'ring', fill: 'red', text: 'disconnected' });\n- }\n-\n- get eventsClient() {\n- return this.reach('nodeConfig.server.events');\n- }\n-\n- get isConnected() {\n- return this.eventsClient && this.eventsClient.connected;\n- }\n}\nRED.nodes.registerType('server-events', ServerEventsNode);\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/server-events-state-changed/server-events-state-changed.js",
"new_path": "nodes/server-events-state-changed/server-events-state-changed.js",
"diff": "-const BaseNode = require('../../lib/base-node');\n+const EventsNode = require('../../lib/events-node');\nmodule.exports = function(RED) {\nconst nodeOptions = {\ndebug: true,\nconfig: {\nentityIdFilter: (nodeDef) => nodeDef.entityidfilter ? nodeDef.entityidfilter.split(',').map(f => f.trim()) : null,\n- haltIfState: (nodeDef) => nodeDef.haltifstate ? nodeDef.haltifstate.trim() : null,\n- name: {},\n- server: { isNode: true }\n+ haltIfState: (nodeDef) => nodeDef.haltifstate ? nodeDef.haltifstate.trim() : null\n}\n};\n- class ServerStateChangedNode extends BaseNode {\n+ class ServerStateChangedNode extends EventsNode {\nconstructor(nodeDefinition) {\nsuper(nodeDefinition, RED, nodeOptions);\n-\n- this.listeners = {\n- onHaEventsStateChanged: this.onHaEventsStateChanged.bind(this),\n- onHaEventsClose: this.onHaEventsClose.bind(this),\n- onHaEventsOpen: this.onHaEventsOpen.bind(this),\n- onHaEventsError: this.onHaEventsError.bind(this)\n- };\n-\n- this.setConnectionStatus(this.isConnected);\n-\n- if (this.eventsClient) {\n- this.eventsClient.addListener('ha_events:state_changed', this.listeners.onHaEventsStateChanged);\n- this.eventsClient.addListener('ha_events:close', this.listeners.onHaEventsClose);\n- this.eventsClient.addListener('ha_events:open', this.listeners.onHaEventsOpen);\n- this.eventsClient.addListener('ha_events:error', this.listeners.onHaEventsError);\n- }\n- }\n-\n- onClose(nodeRemoved) {\n- if (this.eventsClient) {\n- this.eventsClient.removeListener('ha_events:state_changed', this.listeners.onHaEventsStateChanged);\n- this.eventsClient.removeListener('ha_events:close', this.listeners.onHaEventsClose);\n- this.eventsClient.removeListener('ha_events:open', this.listeners.onHaEventsOpen);\n- this.eventsClient.removeListener('ha_events:error', this.listeners.onHaEventsError);\n- }\n+ this.addEventClientListener({ event: 'ha_events:state_changed', handler: this.onHaEventsStateChanged.bind(this) });\n}\nonHaEventsStateChanged (evt) {\n@@ -77,17 +51,6 @@ module.exports = function(RED) {\n}\n}\n- onHaEventsClose() {\n- this.setConnectionStatus(false);\n- }\n- onHaEventsOpen() {\n- this.setConnectionStatus(true);\n- }\n-\n- onHaEventsError(err) {\n- if (err.message) this.error(err.message);\n- }\n-\nshouldHaltIfState (haEvent, haltIfState) {\nif (!this.nodeConfig.haltIfState) return false;\nconst shouldHalt = (this.nodeConfig.haltIfState === haEvent.new_state.state);\n@@ -99,20 +62,6 @@ module.exports = function(RED) {\nconst found = this.nodeConfig.entityIdFilter.filter(filterStr => (entityId.indexOf(filterStr) >= 0));\nreturn found.length > 0;\n}\n-\n- setConnectionStatus(isConnected) {\n- (isConnected)\n- ? this.setStatus({ shape: 'dot', fill: 'green', text: 'connected' })\n- : this.setStatus({ shape: 'ring', fill: 'red', text: 'disconnected' });\n- }\n-\n- get eventsClient() {\n- return this.reach('nodeConfig.server.events');\n- }\n-\n- get isConnected() {\n- return this.eventsClient && this.eventsClient.connected;\n- }\n}\nRED.nodes.registerType('server-state-changed', ServerStateChangedNode);\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Centralized event based logic into base EventNode class |
748,240 | 01.02.2018 19:56:56 | 18,000 | 2a5d5df315bbce6f75e5c0db1ee44a24912cb5e4 | fixed connection/re-connection issue and states cache problem after restart | [
{
"change_type": "MODIFY",
"old_path": "nodes/config-server/config-server.js",
"new_path": "nodes/config-server/config-server.js",
"diff": "@@ -39,21 +39,6 @@ module.exports = function(RED) {\nconstructor(nodeDefinition) {\nsuper(nodeDefinition, RED, nodeOptions);\n- if (this.nodeConfig.url && !this.homeAssistant) {\n- this.homeAssistant = new HomeAssistant({ baseUrl: this.nodeConfig.url, apiPass: this.nodeConfig.pass }, { startListening: true });\n- this.api = this.homeAssistant.api;\n- this.events = this.homeAssistant.events;\n-\n- // TODO: Run modify node-home-assistant to return error in testConnection()\n- // then swap out for real connection test, set startListening above to false\n- // const testConnection = () => Promise.resolve(true);\n- // testConnection()\n- // .then(() => {\n- // this.events.startListening();\n- // })\n- // .catch(err => this.error(err));\n- }\n-\nthis.RED.httpAdmin.get('/homeassistant/entities', httpHandlers.getEntities.bind(this));\nthis.RED.httpAdmin.get('/homeassistant/states', httpHandlers.getStates.bind(this));\nthis.RED.httpAdmin.get('/homeassistant/services', httpHandlers.getServices.bind(this));\n@@ -61,6 +46,55 @@ module.exports = function(RED) {\nconst HTTP_STATIC_OPTS = { root: require('path').join(__dirname, '..', '/_static'), dotfiles: 'deny' };\nthis.RED.httpAdmin.get('/homeassistant/static/*', function(req, res) { res.sendFile(req.params[0], HTTP_STATIC_OPTS) });\n+\n+ if (this.nodeConfig.url && !this.homeAssistant) {\n+ this.homeAssistant = new HomeAssistant({ baseUrl: this.nodeConfig.url, apiPass: this.nodeConfig.pass }, { startListening: false });\n+ this.api = this.homeAssistant.api;\n+ this.events = this.homeAssistant.events;\n+\n+ this.events.addListener('ha_events:close', this.onHaEventsClose.bind(this));\n+ this.events.addListener('ha_events:open', this.onHaEventsOpen.bind(this));\n+ this.events.addListener('ha_events:error', this.onHaEventsError.bind(this));\n+\n+ this.homeAssistant.startListening()\n+ .catch(() => this.startListening());\n+ }\n+ }\n+\n+ // This simply tries to connected every 2 seconds, after the initial connection is successful\n+ // reconnection attempts are handled by node-home-assistant. This could use some love obviously\n+ startListening() {\n+ if (this.connectionAttempts) {\n+ clearInterval(this.connectionAttempts);\n+ this.connectionAttempts = null;\n+ }\n+\n+ this.connectionAttempts = setInterval(() => {\n+ this.homeAssistant.startListening()\n+ .then(() => {\n+ this.debug('Connected to home assistant');\n+ clearInterval(this.connectionAttempts);\n+ this.connectionAttempts = null;\n+ })\n+ .catch(err => this.error(`Home assistant connection failed with error: ${err.message}`));\n+ }, 2000);\n+ }\n+\n+ onHaEventsOpen() {\n+ // This is another hack that should be set in node-home-assistant\n+ // when the connection is first made the states cache needs to be refreshed\n+ this.api.getStates(null, { forceRefresh: true });\n+ this.api.getServices({ forceRefresh: true });\n+ this.api.getEvents({ forceRefresh: true });\n+ this.debug('config server event listener connected');\n+ }\n+\n+ onHaEventsClose() {\n+ this.debug('config server event listener closed');\n+ }\n+\n+ onHaEventsError(err) {\n+ this.debug(err);\n}\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | fixed connection/re-connection issue and states cache problem after restart |
748,240 | 04.02.2018 00:52:32 | 18,000 | 906619010b2d9a85c7d61972b6d4a3baebb5aeb7 | workaround for nodemon --inspect crashing intermitently during restarts due to debugger port being in use | [
{
"change_type": "MODIFY",
"old_path": "_docker/node-red/root-fs/app/nodemon.json",
"new_path": "_docker/node-red/root-fs/app/nodemon.json",
"diff": "{\n\"colours\": true,\n- \"delay\": 1,\n+ \"delay\": \"750\",\n\"verbose\": false,\n\"watch\": [\n\"/data/node_modules/node-red-contrib-home-assistant\"\n],\n+ \"ignore\": [\n+ \"/data/node_modules/node-red-contrib-home-assistant/node_modules\",\n+ \"/data/node_modules/node-red-contrib-home-assistant/_docker\",\n+ \"/data/node_modules/node-red-contrib-home-assistant/_docker-volumes\"\n+ ],\n\"env\": {\n\"NODE_ENV\": \"development\"\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "_docker/node-red/root-fs/app/package.json",
"new_path": "_docker/node-red/root-fs/app/package.json",
"diff": "\"main\": \"node_modules/node-red/red/red.js\",\n\"scripts\": {\n\"start\": \"node $NODE_OPTIONS /app/node_modules/node-red/red.js -v --userDir $USER_DIR $FLOWS\",\n- \"dev:watch\": \"/app/node_modules/.bin/nodemon --inspect=0.0.0.0:9229 --config $NODEMON_CONFIG /app/node_modules/node-red/red.js -- -v --userDir $USER_DIR $FLOWS\"\n+ \"dev:watch\": \"/app/node_modules/.bin/nodemon --config $NODEMON_CONFIG --exec 'sleep 1; node --inspect=0.0.0.0:9229 /app/node_modules/node-red/red.js -v --userDir $USER_DIR $FLOWS'\"\n},\n\"dependencies\": {\n\"node-red\": \"0.17.5\",\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | workaround for nodemon --inspect crashing intermitently during restarts due to debugger port being in use |
748,240 | 04.02.2018 01:47:58 | 18,000 | ed4344f89eb62b5d5345d39dd36421f6ef4734ef | server-state-change node now allows filtering by substring array(old behavior and default), exact match or regex types | [
{
"change_type": "MODIFY",
"old_path": ".gitignore",
"new_path": ".gitignore",
"diff": "@@ -5,3 +5,4 @@ _scratchpad\nsettings.js\n_scratchpad_flows\n.DS_Store\n+_docker-volumes/\n"
},
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -57,6 +57,16 @@ b. _Note: Also first run load of HomeAssistant web interface seems very slow, bu\n| mqtt-listener | | debug listener subscribed to topic `dev/#` of `mqtt` broker for log output |\n| mqtt-dev-sensor | | publishes every 10 seconds to a topic home assistant has a `sensor` platform for |\n| mqtt-dev-binary-sensor | | publishes every 30 seconds to a topic home assistant has a `binary_sensor` for |\n+### Docker Tips\n+1. If you run into environment issues running `npm run dev:clean` should remove all docker data and get you back to a clean state\n+2. All data will be discarded when the docker container is removed. You can map volumes locally to persist data. Create and copy as directed below then modify `docker-compose.yaml` to map the container directories to the created host dirs below. _See: `./_docker/docker-compose.mapped.yaml` for an example or just use that file to launch manually_\n+\n+```\n+mkdir -p _docker-volumes/home-assistant/config\n+mkdir -p _docker-volumes/node-red/data\n+cp _docker/home-assistant/root-fs/config/* _docker-volumes/home-assistant/config/\n+cp _docker/node-red/root-fs/data/* _docker-volumes/node-red/data\n+```\n### Node Debugger via VSCode\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "_docker/docker-compose.mapped.yml",
"diff": "+version: '3.1'\n+\n+services:\n+ mqtt:\n+ container_name: mqtt\n+ env_file: ./config.env\n+ image: mqtt:local\n+ build:\n+ context: ./mqtt\n+ ports:\n+ - 1883:1883\n+ - 9001:9001\n+\n+ mqtt-listener:\n+ image: mqtt:local\n+ container_name: mqtt-listener\n+ command: /listener-cmd.sh\n+ env_file: ./config.env\n+ depends_on:\n+ - mqtt\n+\n+ mqtt-dev-sensor:\n+ image: mqtt:local\n+ container_name: mqtt-dev-sensor\n+ command: /dev-sensor.sh\n+ env_file: ./config.env\n+ depends_on:\n+ - mqtt\n+\n+ mqtt-dev-binary-sensor:\n+ image: mqtt:local\n+ container_name: mqtt-dev-binary-sensor\n+ command: /dev-binary-sensor.sh\n+ env_file: ./config.env\n+ depends_on:\n+ - mqtt\n+\n+ node-red:\n+ container_name: node-red\n+ env_file: ./config.env\n+ build:\n+ context: ./node-red\n+ command: npm run dev:watch\n+ volumes:\n+ - '..:/data/node_modules/node-red-contrib-home-assistant'\n+ - '../_docker-volumes/node-red/data/flows.json:/data/flows.json'\n+ - '../_docker-volumes/node-red/data/settings.js:/data/settings.js'\n+ - '../_docker-volumes/node-red/data/settings.js:/data/package.json'\n+ ports:\n+ - 1880:1880\n+ - 9123:9229\n+\n+ home-assistant:\n+ container_name: home-assistant\n+ env_file: ./config.env\n+ build:\n+ context: ./home-assistant\n+ volumes:\n+ - '../_docker-volumes/home-assistant/config/configuration.yaml:/config/configuration.yaml'\n+ ports:\n+ - 8300:8300\n+ - 8123:8123\n+ depends_on:\n+ - mqtt\n+\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/server-events-state-changed/server-events-state-changed.html",
"new_path": "nodes/server-events-state-changed/server-events-state-changed.html",
"diff": "name: { value: '' },\nserver: { value: '', type: 'server', required: true },\nentityidfilter: { value: '' },\n+ entityidfiltertype: { value: '' },\nhaltifstate: { value: '' }\n},\ninputs: 0,\npaletteLabel: 'events: state',\nlabel: function() { return this.name || `state_changed: ${this.entityidfilter || 'all entities'}` },\noneditprepare: function () {\n- const $entityIdField = $('#node-input-entityidfilter');\n- const $serverField = $('#node-input-server');\n- $entityIdField.val(this.entityidfilter);\n+ const $entityidfilter = $('#node-input-entityidfilter');\n+ const $entityidfiltertype = $('#node-input-entityidfiltertype');\n+ const $server = $('#node-input-server');\n+\n+ $entityidfilter.val(this.entityidfilter);\n+ this.entityidfiltertype = this.entityidfiltertype || 'substring';\n+ $entityidfiltertype.val(this.entityidfiltertype);\n+ $entityidfilter.val(this.entityidfilter);\nconst setupAutocomplete = (node) => {\n- const selectedServer = $serverField.val();\n+ const selectedServer = $server.val();\n// A home assistant server is selected in the node config\nif (node.server || (selectedServer && selectedServer !== '_ADD_')) {\n$.get('/homeassistant/entities').done((entities) => {\nnode.availableEntities = JSON.parse(entities);\n- $entityIdField.autocomplete({ source: node.availableEntities, minLength: 0 });\n+ $entityidfilter.autocomplete({ source: node.availableEntities, minLength: 0 });\n})\n.fail((err) => RED.notify(err.responseText, 'error'));\n}\n};\n- $serverField.change(() => setupAutocomplete(this));\n+ $server.change(() => setupAutocomplete(this));\n},\noneditsave: function() {\nthis.entityidfilter = $(\"#node-input-entityidfilter\").val();\n<script type=\"text/x-red\" data-template-name=\"server-state-changed\">\n+ <!-- Name -->\n<div class=\"form-row\">\n<label for=\"node-input-name\"><i class=\"fa fa-tag\"></i> Name</label>\n<input type=\"text\" id=\"node-input-name\" placeholder=\"Name\">\n</div>\n+ <!-- Server -->\n<div class=\"form-row\">\n<label for=\"node-input-server\"><i class=\"fa fa-server\"></i> Server</label>\n<input type=\"text\" id=\"node-input-server\" />\n</div>\n+ <!-- Entity ID Filter and Filter Type -->\n<div class=\"form-row\">\n- <label for=\"node-input-entityidfilter\"><i class=\"fa fa-filter\"></i> EntityID Filter</label>\n- <input type=\"text\" id=\"node-input-entityidfilter\" placeholder=\"binary_sensor\"/>\n+ <label for=\"node-input-entityidfilter\"><i class=\"fa fa-tag\"></i> Entity ID</label>\n+\n+ <input type=\"text\" id=\"node-input-entityidfilter\" placeholder=\"binary_sensor\" style=\"width: 50%;\" />\n+\n+ <select type=\"text\" id=\"node-input-entityidfiltertype\" style=\"width: 20%;\">\n+ <option value=\"exact\">Exact</option>\n+ <option value=\"substring\">Substring</option>\n+ <option value=\"regex\">Regex</option>\n+ </select>\n</div>\n<div class=\"form-row\">\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/server-events-state-changed/server-events-state-changed.js",
"new_path": "nodes/server-events-state-changed/server-events-state-changed.js",
"diff": "@@ -4,7 +4,14 @@ module.exports = function(RED) {\nconst nodeOptions = {\ndebug: true,\nconfig: {\n- entityIdFilter: (nodeDef) => nodeDef.entityidfilter ? nodeDef.entityidfilter.split(',').map(f => f.trim()) : null,\n+ entityidfilter: (nodeDef) => {\n+ if (!nodeDef.entityidfilter) return undefined;\n+\n+ if (nodeDef.entityidfiltertype === 'substring') return nodeDef.entityidfilter.split(',').map(f => f.trim());\n+ if (nodeDef.entityidfiltertype === 'regex') return new RegExp(nodeDef.entityidfilter);\n+ return nodeDef.entityidfilter;\n+ },\n+ entityidfiltertype: {},\nhaltIfState: (nodeDef) => nodeDef.haltifstate ? nodeDef.haltifstate.trim() : null\n}\n};\n@@ -58,10 +65,23 @@ module.exports = function(RED) {\n}\nshouldIncludeEvent (entityId) {\n- if (!this.nodeConfig.entityIdFilter) return true;\n- const found = this.nodeConfig.entityIdFilter.filter(filterStr => (entityId.indexOf(filterStr) >= 0));\n+ if (!this.nodeConfig.entityidfilter) return true;\n+ const filter = this.nodeConfig.entityidfilter;\n+ const type = this.nodeConfig.entityidfiltertype;\n+\n+ if (type === 'exact') {\n+ return filter === entityId;\n+ }\n+\n+ if (type === 'substring') {\n+ const found = this.nodeConfig.entityidfilter.filter(filterStr => (entityId.indexOf(filterStr) >= 0));\nreturn found.length > 0;\n}\n+\n+ if (type === 'regex') {\n+ return filter.test(entityId);\n+ }\n+ }\n}\nRED.nodes.registerType('server-state-changed', ServerStateChangedNode);\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"docker:down\": \"npm run docker -- down -vt5 && npm run docker -- rm -fv\",\n\"docker:restart\": \"npm run docker -- restart\",\n\"docker:logs\": \"npm run docker -- logs -f && true\",\n- \"docker\": \"docker-compose -f _docker/docker-compose.yml\"\n+ \"docker\": \"docker-compose -f _docker/docker-compose.yml\",\n+ \"docker-map\": \"docker-compose -f _docker/docker-compose.mapped.yml\"\n},\n\"repository\": {\n\"type\": \"git\",\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | #26 - server-state-change node now allows filtering by substring array(old behavior and default), exact match or regex types |
748,240 | 05.02.2018 14:04:12 | 18,000 | 57b4bae7020d8ad26b57f0717fda5ed31b834002 | new 'trigger' node to reduce repetitive node sequences | [
{
"change_type": "MODIFY",
"old_path": "_docker/config.env",
"new_path": "_docker/config.env",
"diff": "+NODE_ENV=development\n+DEBUG=home-assistant*\n+\nHA_HOME_ASSISTANT_TIME_ZONE=America/New_York\nHA_HOME_ASSISTANT_LATITUDE=42.360082\nHA_HOME_ASSISTANT_LONGITUDE=-71.058880\n"
},
{
"change_type": "MODIFY",
"old_path": "_docker/node-red/root-fs/app/nodemon.json",
"new_path": "_docker/node-red/root-fs/app/nodemon.json",
"diff": "{\n\"colours\": true,\n- \"delay\": \"750\",\n+ \"delay\": \"300\",\n\"verbose\": false,\n\"watch\": [\n\"/data/node_modules/node-red-contrib-home-assistant\"\n"
},
{
"change_type": "MODIFY",
"old_path": "_docker/node-red/root-fs/app/package.json",
"new_path": "_docker/node-red/root-fs/app/package.json",
"diff": "\"main\": \"node_modules/node-red/red/red.js\",\n\"scripts\": {\n\"start\": \"node $NODE_OPTIONS /app/node_modules/node-red/red.js -v --userDir $USER_DIR $FLOWS\",\n- \"dev:watch\": \"/app/node_modules/.bin/nodemon --config $NODEMON_CONFIG --exec 'sleep 1; node --inspect=0.0.0.0:9229 /app/node_modules/node-red/red.js -v --userDir $USER_DIR $FLOWS'\"\n+ \"dev:watch\": \"/app/node_modules/.bin/nodemon --config $NODEMON_CONFIG --exec 'sleep 0.5; node --inspect=0.0.0.0:9229 /app/node_modules/node-red/red.js -v --userDir $USER_DIR $FLOWS'\"\n},\n\"dependencies\": {\n\"node-red\": \"0.17.5\",\n"
},
{
"change_type": "ADD",
"old_path": "nodes/trigger-state/icons/trigger.png",
"new_path": "nodes/trigger-state/icons/trigger.png",
"diff": "Binary files /dev/null and b/nodes/trigger-state/icons/trigger.png differ\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "nodes/trigger-state/trigger-state.html",
"diff": "+<script type=\"text/x-red\" data-template-name=\"trigger-state\">\n+ <!-- Name -->\n+ <div class=\"form-row\">\n+ <label for=\"node-input-name\"><i class=\"fa fa-tag\"></i> Name</label>\n+ <input type=\"text\" id=\"node-input-name\" placeholder=\"Name\">\n+ </div>\n+\n+ <!-- Server -->\n+ <div class=\"form-row\">\n+ <label for=\"node-input-server\"><i class=\"fa fa-server\"></i> Server</label>\n+ <input type=\"text\" id=\"node-input-server\" />\n+ </div>\n+\n+ <!-- Entity ID Filter and Filter Type -->\n+ <div class=\"form-row\">\n+ <label for=\"node-input-entityid\"><i class=\"fa fa-tag\"></i> Entity ID</label>\n+ <input type=\"text\" id=\"node-input-entityid\" placeholder=\"binary_sensor\" style=\"width: 50%;\" />\n+ </div>\n+\n+ <!-- Add Constraint -->\n+ <div class=\"form-row\" id=\"add-constraint-container\">\n+ <h3>Add Constraints</h3>\n+ <div>\n+ <!-- Target Selection -->\n+ <div class=\"form-row\">\n+ <!-- Type -->\n+ <select type=\"text\" id=\"constraint-target-type\" style=\"width: 140px;\">\n+ <option value=\"this_entity\">This Entity</option>\n+ <option value=\"entity_id\">Entity ID</option>\n+ </select>\n+\n+ <!-- Value -->\n+ <input type=\"text\" id=\"constraint-target-value\" style=\"width: 62%\" disabled />\n+ </div>\n+\n+ <!-- Property Selection -->\n+ <div class=\"form-row\">\n+ <!-- Type -->\n+ <select type=\"text\" id=\"constraint-property-type\" style=\"width: 140px;\">\n+ <option value=\"current_state\">Current State</option>\n+ <option value=\"previous_state\">Previous State</option>\n+ <option value=\"property\">Property</option>\n+ </select>\n+\n+ <!-- Value -->\n+ <input type=\"text\" id=\"constraint-property-value\" style=\"width: 62%\" disabled />\n+ </div>\n+\n+\n+ <!-- Comparator Selection -->\n+ <div class=\"form-row\">\n+ <!-- Type -->\n+ <select type=\"text\" id=\"constraint-comparator-type\" style=\"width: 140px;\">\n+ <option value=\"is\">Is</option>\n+ <option value=\"is_not\">Is Not</option>\n+\n+ <option value=\"greater_than\">Greater Than</option>\n+ <option value=\"less_than\">Less Than</option>\n+\n+ <option value=\"includes\">Includes</option>\n+ <option value=\"does_not_include\">Does Not Include</option>\n+ </select>\n+\n+ <!-- Value -->\n+ <input type=\"text\" id=\"constraint-comparator-value\" style=\"width: 62%\" />\n+ </div>\n+\n+ <!-- Add Constraint Button -->\n+ <button id=\"constraint-add-btn\" style=\"width: 100%\">Add Constraint</button>\n+ </div>\n+\n+ <!-- Add Custom Outputs -->\n+ <h3>Add Outputs</h3>\n+ <div>\n+ <!-- Output Comparator Selection -->\n+ <div class=\"form-row\">\n+ <label for=\"output-comparator-type\" style=\"width: 60px\"> State</label>\n+\n+ <!-- Type -->\n+ <select type=\"text\" id=\"output-comparator-type\" style=\"width: 140px;\">\n+ <option value=\"is\">Is</option>\n+ <option value=\"is_not\">Is Not</option>\n+\n+ <option value=\"greater_than\">Greater Than</option>\n+ <option value=\"less_than\">Less Than</option>\n+\n+ <option value=\"includes\">Includes</option>\n+ <option value=\"does_not_include\">Does Not Include</option>\n+ </select>\n+\n+ <!-- Value -->\n+ <input type=\"text\" id=\"output-comparator-value\" style=\"width: 45%\" />\n+ </div>\n+\n+ <!-- Add Output Button -->\n+ <button id=\"output-add-btn\" style=\"width: 100%\">Add Output</button>\n+ </div>\n+ </div>\n+\n+ <!-- Constraints List -->\n+ <div class=\"form-row\">\n+ <h6>Constraints</h6>\n+ <ol id=\"constraint-list\"></ol>\n+ </div>\n+\n+ <!-- Constraints List -->\n+ <div class=\"form-row\">\n+ <h6>Custom Outputs</h6>\n+ <ol id=\"output-list\"></ol>\n+ </div>\n+\n+</script>\n+\n+\n+<script type=\"text/javascript\">\n+ RED.nodes.registerType('trigger-state', {\n+ category: 'home_assistant',\n+ color: '#038FC7',\n+ defaults: {\n+ name: { value: '' },\n+ server: { value: '', type: 'server', required: true },\n+ entityid: { value: '', required: true },\n+ constraints: { value: [] },\n+ outputs: { value: 2 },\n+ customoutputs: { value: [] }\n+ },\n+ inputs: 0,\n+ outputs: 2,\n+ outputLabels: function(index) {\n+ if (index === 0) return 'allowed';\n+ if (index === 1) return 'blocked';\n+\n+ // Get custom output by length minus default outputs\n+ const customoutput = this.customoutputs[index - 2];\n+ return `${customoutput.comparatorType.replace('_', '')} ${customoutput.comparatorValue}`;\n+ },\n+ icon: \"trigger.png\",\n+ paletteLabel: 'trigger: state',\n+ label: function() { return this.name || `trigger-state: ${this.entityid}` },\n+ oneditprepare: function () {\n+ const $entityid = $('#node-input-entityid');\n+ const $server = $('#node-input-server');\n+\n+ const getRandomId = () => Math.random().toString(36).slice(2);\n+\n+ $entityid.val(this.entityid);\n+\n+ const setupAutocomplete = (node) => {\n+ const selectedServer = $server.val();\n+\n+ // A home assistant server is selected in the node config\n+ if (node.server || (selectedServer && selectedServer !== '_ADD_')) {\n+ $.get('/homeassistant/entities').done((entities) => {\n+ node.availableEntities = JSON.parse(entities);\n+ $entityid.autocomplete({ source: node.availableEntities, minLength: 0 });\n+ })\n+ .fail((err) => RED.notify(err.responseText, 'error'));\n+ }\n+ };\n+\n+ $server.change(() => setupAutocomplete(this));\n+\n+ // **************************\n+ // * Add Constraints\n+ // **************************\n+ const $constraints = {\n+ list: $('#constraint-list'),\n+ container: $('#add-constraint-container'),\n+ addBtn: $('#constraint-add-btn'),\n+\n+ targetType: $('#constraint-target-type'),\n+ targetValue: $('#constraint-target-value'),\n+ propertyType: $('#constraint-property-type'),\n+ propertyValue: $('#constraint-property-value'),\n+ comparatorType: $('#constraint-comparator-type'),\n+ comparatorValue: $('#constraint-comparator-value')\n+ };\n+\n+ $constraints.container.accordion({ active: false, collapsible: true, heightStyle: 'content' });\n+\n+ // Constraint select menu change handlers\n+ $constraints.targetType.on('change', function (e) {\n+ const val = e.target.value;\n+ (val === 'this_entity')\n+ ? $constraints.targetValue.attr('disabled', 'disabled')\n+ : $constraints.targetValue.removeAttr('disabled')\n+ });\n+ $constraints.propertyType.on('change', function (e) {\n+ const val = e.target.value;\n+ (val === 'current_state' || val === 'previous_state')\n+ ? $constraints.propertyValue.attr('disabled', 'disabled')\n+ : $constraints.propertyValue.removeAttr('disabled');\n+ });\n+ $constraints.comparatorType.on('change', function (e) {\n+ const val = e.target.value;\n+ console.log('comparator type changed to: ', val);\n+ });\n+ // TODO: Add debounced change handler for input that validates on keyup and marks field invalid, disable/enables add button\n+ // TODO: Disabled add button initially\n+\n+ // Constraint Add Button\n+ $constraints.addBtn.on('click', function() {\n+ const constraint = {\n+ id: getRandomId(),\n+ targetType: $constraints.targetType.val(),\n+ targetValue: $constraints.targetValue.val(),\n+ propertyType: $constraints.propertyType.val(),\n+ propertyValue: $constraints.propertyValue.val(),\n+ comparatorType: $constraints.comparatorType.val(),\n+ comparatorValue: $constraints.comparatorValue.val()\n+ };\n+\n+ if (constraint.propertyType === 'current_state') constraint.propertyValue = 'new_state.state';\n+ if (constraint.propertyType === 'previous_state') constraint.propertyValue = 'old_state.state';\n+\n+ $constraints.list.editableList('addItem', constraint);\n+ $constraints.targetValue.val('');\n+ });\n+\n+ // Constraints List\n+ $constraints.list.editableList({\n+ addButton: false,\n+ height: 159,\n+ sortable: true,\n+ removable: true,\n+ removeItem( data ) {\n+ console.log('Item removed', data);\n+ },\n+ addItem: function(row, index, data) {\n+ console.log('Adding item data: ', data);\n+ const $row = $(row);\n+ const { targetType, targetValue, propertyType, propertyValue, comparatorType, comparatorValue } = data;\n+\n+ const entityText = (targetType === 'this_entity') ? 'this entity' : targetValue;\n+ const propertyText = (propertyType === 'property') ? propertyText : propertyType.replace('_', ' ');\n+\n+ const comparatorTypeText = comparatorType.replace('_', ' ');\n+\n+ const rowHtml = `\n+ <strong>${entityText}:</strong> ${propertyText} ${comparatorTypeText} ${comparatorValue}\n+ `;\n+\n+ $row.html(rowHtml);\n+ }\n+ });\n+\n+ // Add previous constraints to list\n+ this.constraints.forEach(c => $constraints.list.editableList('addItem', c));\n+\n+ // **************************\n+ // * Add Custom Outputs\n+ // **************************\n+ const $customoutputs = {\n+ list: $('#output-list'),\n+ comparatorType: $('#output-comparator-type'),\n+ comparatorValue: $('#output-comparator-value'),\n+ addBtn: $('#output-add-btn')\n+ };\n+\n+ // Outputs Add Button\n+ $customoutputs.addBtn.on('click', function() {\n+ const output = {\n+ comparatorType: $customoutputs.comparatorType.val(),\n+ comparatorValue: $customoutputs.comparatorValue.val()\n+ };\n+\n+ $customoutputs.list.editableList('addItem', output);\n+ });\n+\n+ // Outputs List\n+ $customoutputs.list.editableList({\n+ addButton: false,\n+ height: 159,\n+ sortable: false,\n+ removable: true,\n+ removeItem( data ) {\n+ console.log('Item removed', data);\n+ },\n+ addItem: function(row, index, data) {\n+ console.log('Adding output data: ', data);\n+ const $row = $(row);\n+ const { comparatorType, comparatorValue } = data;\n+\n+ const comparatorTypeText = comparatorType.replace('_', ' ');\n+\n+ const rowHtml = `\n+ Incoming state ${comparatorTypeText} ${comparatorValue}\n+ `;\n+\n+ $row.html(rowHtml);\n+ }\n+ });\n+\n+ // Add previous outputs to list\n+ this.customoutputs.forEach(o => $customoutputs.list.editableList('addItem', o));\n+ },\n+ oneditsave: function() {\n+ const $constraintsList = $('#constraint-list');\n+ const $outputList = $('#output-list');\n+ const $entityid = $('#node-input-entityid');\n+\n+ this.entityid = $entityid.val();\n+\n+ // Compile Constraints\n+ const nodeConstraints = [];\n+ const listConstraints = $constraintsList.editableList('items');\n+ listConstraints.each(function(i) { nodeConstraints.push($(this).data('data')); });\n+ this.constraints = nodeConstraints;\n+\n+ // Compile Outputs\n+ const nodeOutputs = [];\n+ const listOutputs = $outputList.editableList('items');\n+ listOutputs.each(function(i) { nodeOutputs.push($(this).data('data')); });\n+ this.customoutputs = nodeOutputs;\n+\n+ this.outputs = this.customoutputs.length + 2;\n+ },\n+ // oneditresize: function(size) {\n+ // var rows = $(\"#dialog-form>div:not(.node-input-rule-container-row)\");\n+ // var height = size.height;\n+ // for (var i=0;i<rows.size();i++) {\n+ // height -= $(rows[i]).outerHeight(true);\n+ // }\n+ // var editorRow = $(\"#dialog-form>div.node-input-rule-container-row\");\n+ // height -= (parseInt(editorRow.css(\"marginTop\"))+parseInt(editorRow.css(\"marginBottom\")));\n+ // $(\"#node-input-rule-container\").editableList('height',height);\n+ // }\n+ });\n+</script>\n+\n+\n+\n+\n+<script type=\"text/x-red\" data-help-name=\"trigger-state\">\n+ <p class=\"ha-description\">Advanced version of 'server:state-changed' node</p>\n+\n+ <h4 class=\"ha-title\">Configuration:</h4>\n+ <table class=\"ha-table\" style=\"width: 100%;\" border=\"1\" cellpadding=\"10\">\n+ <tbody>\n+ <tr> <td>Entity ID Filter</td> <td>Exact match for entity_id field</td> </tr>\n+ </tbody>\n+ </table>\n+\n+ <br/>\n+\n+ <h4 class=\"ha-title\">Output Object:</h4>\n+ <table class=\"ha-table\" style=\"width: 100%;\" border=\"1\" cellpadding=\"10\">\n+ <tbody>\n+ <tr> <td>topic</td> <td>entity_id (e.g.: sensor.bedroom_temp)</td> </tr>\n+ <tr> <td>payload</td> <td>event.current_state.state (e.g.: 'on', 'off', '88.5', 'home', 'not_home')</td> </tr>\n+ <tr> <td>data</td> <td>original event object from homeassistant</td> </tr>\n+ </tbody>\n+ </table>\n+</script>\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "nodes/trigger-state/trigger-state.js",
"diff": "+const EventsNode = require('../../lib/events-node');\n+\n+module.exports = function(RED) {\n+ const nodeOptions = {\n+ debug: true,\n+ config: {\n+ entityid: {},\n+ constraints: {},\n+ customoutputs: {}\n+ }\n+ };\n+\n+ class TriggerState extends EventsNode {\n+ constructor(nodeDefinition) {\n+ super(nodeDefinition, RED, nodeOptions);\n+ const eventTopic = `ha_events:state_changed:${this.nodeConfig.entityid}`;\n+ this.addEventClientListener({ event: eventTopic, handler: this.onEntityStateChanged.bind(this) });\n+ }\n+\n+ async getConstraintTargetData(constraint, triggerEvent) {\n+ let targetData = { entityid: null, state: null };\n+\n+ try {\n+ const isTargetThisEntity = constraint.targetType === 'this_entity';\n+ targetData.entityid = (isTargetThisEntity) ? this.nodeConfig.entityid : constraint.targetValue;\n+\n+ // TODO: Non 'self' targets state is just new_state of an incoming event, wrap to hack around the fact\n+ // NOTE: UI needs changing to handle this there, and also to hide \"previous state\" if target is not self\n+ if (isTargetThisEntity) {\n+ targetData.state = triggerEvent;\n+ } else {\n+ const state = await this.nodeConfig.server.api.getStates(targetData.entityid);\n+ targetData.state = {\n+ new_state: state[targetData.entityid]\n+ };\n+ }\n+ } catch (e) {\n+ this.debug('Error during trigger:state comparator evalutation: ', e.stack);\n+ throw e;\n+ }\n+\n+ return targetData;\n+ }\n+\n+ /* eslint-disable indent */\n+ getComparatorResult(comparatorType, comparatorValue, actualValue) {\n+ switch (comparatorType) {\n+ case 'is':\n+ return comparatorValue === actualValue;\n+ case 'is_not':\n+ return comparatorValue !== actualValue;\n+ case 'greater_than':\n+ return comparatorValue > actualValue;\n+ case 'less_than':\n+ return comparatorValue < actualValue;\n+ case 'includes':\n+ case 'does_not_include':\n+ const filterResults = comparatorValue.split(',').filter(cvalue => (cvalue === actualValue));\n+ return (comparatorType === 'includes')\n+ ? filterResults.length > 0\n+ : filterResults.length < 1;\n+ }\n+ }\n+\n+ async onEntityStateChanged (evt) {\n+ try {\n+ const { entity_id, event } = evt;\n+ const { nodeConfig } = this;\n+\n+ const allComparatorResults = [];\n+ let comparatorsAllMatches = true;\n+\n+ // Check constraints\n+ for (let constraint of nodeConfig.constraints) {\n+ const constraintTarget = await this.getConstraintTargetData(constraint, event);\n+ const actualValue = this.utils.reach(constraint.propertyValue, constraintTarget.state);\n+ const comparatorResult = this.getComparatorResult(constraint.comparatorType, constraint.comparatorValue, actualValue);\n+\n+ // If all previous comparators were true and this comparator is true then all matched so far\n+ comparatorsAllMatches = comparatorsAllMatches && comparatorResult;\n+\n+ allComparatorResults.push({ constraint, constraintTarget, actualValue, comparatorResult });\n+ }\n+\n+ const msg = {\n+ topic: entity_id,\n+ payload: event.new_state.state,\n+ data: event\n+ };\n+ let outputs;\n+\n+ if (!comparatorsAllMatches) {\n+ this.debug(`one more more comparators failed to match constraints, flow halted as a result, failed results below: `);\n+\n+ const failedConstraints = allComparatorResults.filter(res => !res.comparatorResult)\n+ .map(res => {\n+ this.debug(`Failed Result: \"${res.constraintTarget.entityid}\" had actual value of \"${res.actualValue}\" which failed an \"${res.constraint.comparatorType}\" check looking for expected value \"${res.constraint.comparatorValue}\"`);\n+ return res;\n+ });\n+ msg.failedConstraints = failedConstraints;\n+ outputs = [null, msg];\n+ } else {\n+ outputs = [msg, null];\n+ }\n+\n+ if (!this.nodeConfig.customoutputs || !this.nodeConfig.customoutputs.length) return this.send(outputs);\n+\n+ // Map output to matched customoutputs\n+ const customoutputMsgs = this.nodeConfig.customoutputs.reduce((acc, output) => {\n+ const actualValue = event.new_state.state;\n+ const comparatorMatched = this.getComparatorResult(output.comparatorType, output.comparatorValue, actualValue);\n+ (comparatorMatched) ? acc.push(msg) : acc.push(null);\n+ return acc;\n+ }, []);\n+ outputs = outputs.concat(customoutputMsgs);\n+\n+ this.send(outputs);\n+ } catch (e) {\n+ this.error(e);\n+ }\n+ }\n+ }\n+\n+ RED.nodes.registerType('trigger-state', TriggerState);\n+};\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"server\": \"nodes/config-server/config-server.js\",\n\"server-events\": \"nodes/server-events-all/server-events-all.js\",\n\"server-state-changed\": \"nodes/server-events-state-changed/server-events-state-changed.js\",\n+ \"trigger-state\": \"nodes/trigger-state/trigger-state.js\",\n\"api-call-service\": \"nodes/api_call-service/api_call-service.js\",\n\"api-current-state\": \"nodes/api_current-state/api_current-state.js\",\n\"api-get-history\": \"nodes/api_get-history/api_get-history.js\",\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | #30 - new 'trigger' node to reduce repetitive node sequences |
748,240 | 06.02.2018 01:09:17 | 18,000 | c85f4d903a28e9e4d2c7136937c34dd6ccd51940 | WIP: Trigger State node | [
{
"change_type": "MODIFY",
"old_path": ".vscode/launch.json",
"new_path": ".vscode/launch.json",
"diff": "\"version\": \"0.2.0\",\n\"configurations\": [\n{\n- \"name\": \"Attach: Docker\",\n+ \"name\": \"Attach Docker: node-red\",\n\"type\": \"node\",\n\"request\": \"attach\",\n\"timeout\": 20000,\n\"localRoot\": \"${workspaceFolder}\",\n\"remoteRoot\": \"/data/node_modules/node-red-contrib-home-assistant\",\n\"trace\": false,\n+ \"skipFiles\": [\n+ \"<node_internals>/**/*.js\"\n+ ]\n+ },\n+\n+ {\n+ \"name\": \"Attach Local: node-red\",\n+ \"type\": \"node\",\n+ \"request\": \"attach\",\n+ \"timeout\": 20000,\n+ \"restart\": true,\n+ \"address\": \"localhost\",\n+ \"port\": 9123,\n+ \"trace\": true,\n+\n\"skipFiles\": [\n\"<node_internals>/**/*.js\"\n]\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/events-node.js",
"new_path": "lib/events-node.js",
"diff": "@@ -19,7 +19,7 @@ class EventsNode extends BaseNode {\nthis.addEventClientListener({ event: 'ha_events:open', handler: this.onHaEventsOpen.bind(this) });\nthis.addEventClientListener({ event: 'ha_events:error', handler: this.onHaEventsError.bind(this) });\n- this.setConnectionStatus(this.isConnected);\n+ // this.setConnectionStatus(this.isConnected);\n}\naddEventClientListener({ event, handler }) {\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/config-server/config-server.js",
"new_path": "nodes/config-server/config-server.js",
"diff": "@@ -5,7 +5,7 @@ module.exports = function(RED) {\nconst httpHandlers = {\ngetEntities: function (req, res, next) {\n- return this.api.getStates()\n+ return this.homeAssistant.getStates()\n.then(states => res.json(JSON.stringify(Object.keys(states))))\n.catch(e => this.error(e.message));\n},\n@@ -83,9 +83,9 @@ module.exports = function(RED) {\nonHaEventsOpen() {\n// This is another hack that should be set in node-home-assistant\n// when the connection is first made the states cache needs to be refreshed\n- this.api.getStates(null, { forceRefresh: true });\n- this.api.getServices({ forceRefresh: true });\n- this.api.getEvents({ forceRefresh: true });\n+ this.homeAssistant.getStates(null, true);\n+ this.homeAssistant.getServices(true);\n+ this.homeAssistant.getEvents(true);\nthis.debug('config server event listener connected');\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.html",
"new_path": "nodes/trigger-state/trigger-state.html",
"diff": "<button id=\"constraint-add-btn\" style=\"width: 100%\">Add Constraint</button>\n</div>\n+ <!-- -------------------------------------------------------------- -->\n<!-- Add Custom Outputs -->\n+ <!-- -------------------------------------------------------------- -->\n<h3>Add Outputs</h3>\n<div>\n+ <div class=\"form-row\">\n+ <label for=\"output-timer-type\" style=\"width: 60px\"> Send</label>\n+\n+ <!-- Type -->\n+ <select type=\"text\" id=\"output-timer-type\" style=\"width: 112px;\">\n+ <option value=\"immediate\"> Immediately </option>\n+ <option value=\"delayed\"> Delayed </option>\n+ </select>\n+\n+ <input type=\"text\" id=\"output-timer-value\" style=\"width: 22%\" disabled />\n+\n+ <select type=\"text\" id=\"output-timer-unit\" style=\"width: 112px;\" disabled>\n+ <option value=\"milliseconds\"> Milliseconds </option>\n+ <option value=\"seconds\"> Seconds </option>\n+ <option value=\"minutes\"> Minutes </option>\n+ <option value=\"hours\"> Hours </option>\n+ </select>\n+ </div>\n+\n+ <div class=\"form-row\">\n+ <label for=\"output-message-type\" style=\"width: 60px\"> Message</label>\n+\n+ <!-- Type -->\n+ <select type=\"text\" id=\"output-message-type\" style=\"width: 112px;\">\n+ <option value=\"default\"> Default Msg </option>\n+ <option value=\"custom\"> Custom Msg </option>\n+ </select>\n+\n+ <input type=\"text\" id=\"output-message-value\" style=\"width: 52%\" disabled/>\n+ </div>\n+\n+\n<!-- Output Comparator Selection -->\n<div class=\"form-row\">\n- <label for=\"output-comparator-type\" style=\"width: 60px\"> State</label>\n+ <label for=\"output-comparator-type\" style=\"width: 60px\"> If</label>\n+\n+ <select type=\"text\" id=\"output-comparator-property-type\" style=\"width: 112px\">\n+ <option value=\"always\"> Always </option>\n+ <option value=\"current_state\"> State </option>\n+ <option value=\"previous_state\"> Prev State </option>\n+ <option value=\"property\"> Property </option>\n+ </select>\n+\n+ <input type=\"text\" id=\"output-comparator-property-value\" style=\"width: 52%\" disabled />\n+ </div>\n+ <div class=\"form-row\">\n<!-- Type -->\n- <select type=\"text\" id=\"output-comparator-type\" style=\"width: 140px;\">\n+ <select type=\"text\" id=\"output-comparator-type\" style=\"width: 140px;\" disabled>\n<option value=\"is\"> Is </option>\n<option value=\"is_not\"> Is Not </option>\n<option value=\"does_not_include\">Does Not Include</option>\n</select>\n- <!-- Value -->\n- <input type=\"text\" id=\"output-comparator-value\" style=\"width: 45%\" />\n+ <input type=\"text\" id=\"output-comparator-value\" style=\"width: 62%\" disabled />\n</div>\n<!-- Add Output Button -->\noutputs: { value: 2 },\ncustomoutputs: { value: [] }\n},\n- inputs: 0,\n+ inputs: 1,\noutputs: 2,\noutputLabels: function(index) {\n+ const NUM_DEFAULT_OUTPUTS = 2;\n+\nif (index === 0) return 'allowed';\nif (index === 1) return 'blocked';\n// Get custom output by length minus default outputs\n- const customoutput = this.customoutputs[index - 2];\n+ const customoutput = this.customoutputs[index - NUM_DEFAULT_OUTPUTS];\nreturn `${customoutput.comparatorType.replace('_', '')} ${customoutput.comparatorValue}`;\n},\nicon: \"trigger.png\",\npaletteLabel: 'trigger: state',\nlabel: function() { return this.name || `trigger-state: ${this.entityid}` },\noneditprepare: function () {\n+ const NUM_DEFAULT_OUTPUTS = 2;\n+\nconst $entityid = $('#node-input-entityid');\nconst $server = $('#node-input-server');\n$entityid.val(this.entityid);\n+ // New nodes, select first available home-assistant config node found\n+ if (!this.server) {\n+ let defaultServer;\n+ RED.nodes.eachConfig(n => {\n+ if (n.type === 'server' && !defaultServer) defaultServer = n.id;\n+ });\n+ if (defaultServer) $server.val(defaultServer);\n+ }\n+\nconst setupAutocomplete = (node) => {\nconst selectedServer = $server.val();\n// **************************\nconst $customoutputs = {\nlist: $('#output-list'),\n+ addBtn: $('#output-add-btn'),\n+\n+ timerType: $('#output-timer-type'),\n+ timerValue: $('#output-timer-value'),\n+ timerUnit: $('#output-timer-unit'),\n+\n+ messageType: $('#output-message-type'),\n+ messageValue: $('#output-message-value'),\n+\n+ comparatorPropertyType: $('#output-comparator-property-type'),\n+ comparatorPropertyValue: $('#output-comparator-property-value'),\ncomparatorType: $('#output-comparator-type'),\n- comparatorValue: $('#output-comparator-value'),\n- addBtn: $('#output-add-btn')\n+ comparatorValue: $('#output-comparator-value')\n};\n// Outputs Add Button\n$customoutputs.addBtn.on('click', function() {\nconst output = {\n+ outputId: getRandomId(),\n+ timerType: $customoutputs.timerType.val(),\n+ timerValue: $customoutputs.timerValue.val(),\n+ timerUnit: $customoutputs.timerUnit.val(),\n+\n+ messageType: $customoutputs.messageType.val(),\n+ messageValue: $customoutputs.messageValue.val(),\n+\n+ comparatorPropertyType: $customoutputs.comparatorPropertyType.val(),\n+ comparatorPropertyValue: $customoutputs.comparatorPropertyValue.val(),\n+\ncomparatorType: $customoutputs.comparatorType.val(),\ncomparatorValue: $customoutputs.comparatorValue.val()\n};\n+ if (output.comparatorPropertyType === 'current_state') output.comparatorPropertyValue = 'new_state.state';\n+ if (output.comparatorPropertyType === 'previous_state') output.comparatorPropertyValue = 'old_state.state';\n+\n$customoutputs.list.editableList('addItem', output);\n});\nconsole.log('Adding output data: ', data);\nconst $row = $(row);\nconst { comparatorType, comparatorValue } = data;\n+ const htmlData = JSON.stringify(data);\n+ $row.html(htmlData);\n+ }\n+ });\n- const comparatorTypeText = comparatorType.replace('_', ' ');\n-\n- const rowHtml = `\n- Incoming state ${comparatorTypeText} ${comparatorValue}\n- `;\n-\n- $row.html(rowHtml);\n+ // Constraint select menu change handlers\n+ $customoutputs.timerType.on('change', function (e) {\n+ const val = e.target.value;\n+ if (val === 'immediate') {\n+ $customoutputs.timerValue.attr('disabled', 'disabled')\n+ $customoutputs.timerUnit.attr('disabled', 'disabled')\n+ } else {\n+ $customoutputs.timerValue.removeAttr('disabled')\n+ $customoutputs.timerUnit.removeAttr('disabled')\n}\n});\n+ $customoutputs.messageType.on('change', function (e) {\n+ const val = e.target.value;\n+ (val === 'default')\n+ ? $customoutputs.messageValue.attr('disabled', 'disabled')\n+ : $customoutputs.messageValue.removeAttr('disabled');\n+ });\n+ $customoutputs.comparatorPropertyType.on('change', function (e) {\n+ const val = e.target.value;\n+ if (val === 'always') {\n+ $customoutputs.comparatorProperty.attr('disabled', 'disabled');\n+ $customoutputs.comparatorType.attr('disabled', 'disabled');\n+ $customoutputs.comparatorValue.attr('disabled', 'disabled');\n+ }\n+ if (val === 'previous_state' || val === 'current_state') {\n+ $customoutputs.comparatorProperty.attr('disabled', 'disabled');\n+ $customoutputs.comparatorType.removeAttr('disabled');\n+ $customoutputs.comparatorValue.removeAttr('disabled');\n+ }\n+ if (val === 'property') {\n+ $customoutputs.comparatorProperty.removeAttr('disabled');\n+ $customoutputs.comparatorType.removeAttr('disabled');\n+ $customoutputs.comparatorValue.removeAttr('disabled');\n+ }\n+\n+ });\n+\n// Add previous outputs to list\nthis.customoutputs.forEach(o => $customoutputs.list.editableList('addItem', o));\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.js",
"new_path": "nodes/trigger-state/trigger-state.js",
"diff": "const EventsNode = require('../../lib/events-node');\n+const TIMER_MULTIPLIERS = {\n+ milliseconds: 1,\n+ seconds: 1000,\n+ minutes: 60000,\n+ hours: 3600000\n+};\n+\nmodule.exports = function(RED) {\nconst nodeOptions = {\ndebug: true,\n@@ -15,6 +22,18 @@ module.exports = function(RED) {\nsuper(nodeDefinition, RED, nodeOptions);\nconst eventTopic = `ha_events:state_changed:${this.nodeConfig.entityid}`;\nthis.addEventClientListener({ event: eventTopic, handler: this.onEntityStateChanged.bind(this) });\n+ this.NUM_DEFAULT_MESSAGES = 2;\n+ this.messageTimers = {};\n+ }\n+ onClose(removed) {\n+ // TODO: test this\n+ if (removed) {\n+ this.debug('removing all message timers onClose and node was removed');\n+ Object.keys(this.messageTimers).forEach(k => {\n+ if (this.messageTimers[k]) clearTimeout(this.messageTimers[k]);\n+ this.messageTimers[k] = null;\n+ });\n+ }\n}\nasync getConstraintTargetData(constraint, triggerEvent) {\n@@ -29,7 +48,7 @@ module.exports = function(RED) {\nif (isTargetThisEntity) {\ntargetData.state = triggerEvent;\n} else {\n- const state = await this.nodeConfig.server.api.getStates(targetData.entityid);\n+ const state = await this.nodeConfig.server.homeAssistant.getStates(targetData.entityid);\ntargetData.state = {\nnew_state: state[targetData.entityid]\n};\n@@ -94,7 +113,7 @@ module.exports = function(RED) {\nconst failedConstraints = allComparatorResults.filter(res => !res.comparatorResult)\n.map(res => {\n- this.debug(`Failed Result: \"${res.constraintTarget.entityid}\" had actual value of \"${res.actualValue}\" which failed an \"${res.constraint.comparatorType}\" check looking for expected value \"${res.constraint.comparatorValue}\"`);\n+ this.debug(`Failed Result: \"${res.constraintTarget.entityid}\" had value of \"${res.actualValue}\" which failed an \"${res.constraint.comparatorType}\" check against expected value \"${res.constraint.comparatorValue}\"`);\nreturn res;\n});\nmsg.failedConstraints = failedConstraints;\n@@ -103,17 +122,61 @@ module.exports = function(RED) {\noutputs = [msg, null];\n}\n- if (!this.nodeConfig.customoutputs || !this.nodeConfig.customoutputs.length) return this.send(outputs);\n+ if (!this.nodeConfig.customoutputs.length) return this.send(outputs);\n// Map output to matched customoutputs\n- const customoutputMsgs = this.nodeConfig.customoutputs.reduce((acc, output) => {\n- const actualValue = event.new_state.state;\n- const comparatorMatched = this.getComparatorResult(output.comparatorType, output.comparatorValue, actualValue);\n- (comparatorMatched) ? acc.push(msg) : acc.push(null);\n+ const customoutputMsgs = this.nodeConfig.customoutputs.reduce((acc, output, reduceIndex) => {\n+ let comparatorMatched = true;\n+\n+ if (output.comparatorPropertyType !== 'always') {\n+ const actualValue = this.utils.reach(output.comparatorPropertyValue, event);\n+ comparatorMatched = this.getComparatorResult(output.comparatorType, output.comparatorPropertyValue, actualValue);\n+ }\n+\n+ let message = (output.messageType === 'default') ? msg : output.messageValue;\n+\n+ // If comparator did not matched no need to go further\n+ if (!comparatorMatched) {\n+ this.debug('Skipping message, output comparator failed');\n+ acc.push(null);\n+ return acc;\n+ }\n+\n+ // If comparator matched and send immediate is set just assign message to output\n+ if (output.timerType === 'immediate') {\n+ acc.push(message);\n+ this.debug('Adding immediate message');\n+ return acc;\n+ }\n+\n+ // If already timer scheduler for this output then clear it for re-setting\n+ if (this.messageTimers[output.outputId]) {\n+ this.debug('Found already scheduled message, extending the message timeout');\n+ clearTimeout(this.messageTimers[output.outputId]);\n+ }\n+\n+ // Get the timer ms value\n+ const timerDelayMs = output.timerValue * TIMER_MULTIPLIERS[output.timerUnit];\n+\n+ // Create the message to send, all outputs leading to this one with null (dont send) values\n+ const customOutputIndexWithDefaults = reduceIndex + this.NUM_DEFAULT_MESSAGES;\n+ const scheduledMessage = (new Array(customOutputIndexWithDefaults + 1)).fill(null);\n+ scheduledMessage[customOutputIndexWithDefaults] = message;\n+ this.debug('Created scheduledMessage: ', scheduledMessage);\n+\n+ this.messageTimers[output.outputId] = setTimeout(() => {\n+ this.debug('Sending delayed message', scheduledMessage);\n+ this.send(scheduledMessage);\n+ delete this.messageTimers[output.outputId];\n+ }, timerDelayMs);\n+\n+ // Since the message was scheduled push null val to current message output list\n+ acc.push(null);\nreturn acc;\n}, []);\n- outputs = outputs.concat(customoutputMsgs);\n+ outputs = outputs.concat(customoutputMsgs);\n+ this.debug('Sending default output messages and any matched custom outputs(if any)');\nthis.send(outputs);\n} catch (e) {\nthis.error(e);\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | WIP: Trigger State node |
748,240 | 06.02.2018 14:28:41 | 18,000 | e276e37a42247a99ff8ec173c0180bfb1ddedfe4 | trigger-state: fix for removing custom output causing node-red wires to be mis-mapped | [
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.html",
"new_path": "nodes/trigger-state/trigger-state.html",
"diff": "<div>\n<div class=\"form-row\">\n<label for=\"output-timer-type\" style=\"width: 60px\"> Send</label>\n+ <input type=\"hidden\" id=\"node-input-outputs\"/> <!-- Needs to exist for node-red output remapping -->\n<!-- Type -->\n<select type=\"text\" id=\"output-timer-type\" style=\"width: 112px;\">\nif (index === 1) return 'blocked';\n// Get custom output by length minus default outputs\n- const customoutput = this.customoutputs[index - NUM_DEFAULT_OUTPUTS];\n- return `${customoutput.comparatorType.replace('_', '')} ${customoutput.comparatorValue}`;\n+ const co = this.customoutputs[index - NUM_DEFAULT_OUTPUTS];\n+ let label = `${co.timerType}: `;\n+ if (co.comparatorPropertyType === 'always') {\n+ label += 'always sent'\n+ } else {\n+ label += `sent when ${co.comparatorPropertyType.replace('_', ' ')} ${co.comparatorType.replace('_', '')} ${co.comparatorValue}`;\n+ }\n+ return label;\n},\nicon: \"trigger.png\",\npaletteLabel: 'trigger: state',\nconst $entityid = $('#node-input-entityid');\nconst $server = $('#node-input-server');\n+ const $outputs = $('#node-input-outputs');\n+\nconst getRandomId = () => Math.random().toString(36).slice(2);\ncomparatorValue: $customoutputs.comparatorValue.val()\n};\n+ // Removing an output and adding in same edit session means output\n+ // map needs to be adjusted, otherwise just increment count\n+ debugger;\n+ if (isNaN(NODE.outputs)) {\n+ // const maxOutput = Math.max(Object.keys(NODE.outputs));\n+ NODE.outputs[getRandomId()] = 'abc';\n+ } else {\n+ NODE.outputs = parseInt(NODE.outputs) + 1;\n+ }\n+ $outputs.val(isNaN(NODE.outputs) ? JSON.parse(NODE.outputs) : NODE.outputs);\n+\nif (output.comparatorPropertyType === 'current_state') output.comparatorPropertyValue = 'new_state.state';\nif (output.comparatorPropertyType === 'previous_state') output.comparatorPropertyValue = 'old_state.state';\n});\n// Outputs List\n+ let NODE = this;\n$customoutputs.list.editableList({\naddButton: false,\nheight: 159,\nremovable: true,\nremoveItem( data ) {\nconsole.log('Item removed', data);\n+ // node-red uses a map of old output index to new output index to re-map\n+ // links between nodes. If new index is -1 then it was removed\n+ let customOutputRemovedIndex = NODE.customoutputs.indexOf(data);\n+ NODE.outputs = !(isNaN(NODE.outputs)) ? { 0: 0, 1: 1 } : NODE.outputs;\n+ NODE.outputs[customOutputRemovedIndex + NUM_DEFAULT_OUTPUTS] = -1;\n+\n+ NODE.customoutputs.forEach((o, customOutputIndex) => {\n+ const customAllIndex = customOutputIndex + NUM_DEFAULT_OUTPUTS;\n+ const outputIsBeforeRemoval = (customOutputIndex < customOutputRemovedIndex);\n+ const customOutputAlreadyMapped = NODE.outputs.hasOwnProperty(customAllIndex);\n+\n+ // If we're on removed output\n+ if (customOutputIndex === customOutputRemovedIndex) return;\n+ // output already removed\n+ if (customOutputAlreadyMapped && NODE.outputs[customAllIndex] === -1) return;\n+ // output previously removed caused this output to be remapped\n+ if (customOutputAlreadyMapped) {\n+ NODE.outputs[customAllIndex] = (outputIsBeforeRemoval)\n+ ? NODE.outputs[customAllIndex]\n+ : NODE.outputs[customAllIndex] - 1;\n+ return;\n+ }\n+\n+ // output exists after removal and hasn't been mapped, remap to current index - 1\n+ NODE.outputs[customAllIndex] = (outputIsBeforeRemoval)\n+ ? customAllIndex\n+ : customAllIndex - 1;\n+ });\n+\n+ $outputs.val(JSON.stringify(NODE.outputs));\n},\naddItem: function(row, index, data) {\nconsole.log('Adding output data: ', data);\nconst $row = $(row);\nconst { comparatorType, comparatorValue } = data;\nconst htmlData = JSON.stringify(data);\n+\n$row.html(htmlData);\n}\n});\n$customoutputs.comparatorPropertyType.on('change', function (e) {\nconst val = e.target.value;\nif (val === 'always') {\n- $customoutputs.comparatorProperty.attr('disabled', 'disabled');\n+ $customoutputs.comparatorPropertyValue.attr('disabled', 'disabled');\n$customoutputs.comparatorType.attr('disabled', 'disabled');\n$customoutputs.comparatorValue.attr('disabled', 'disabled');\n}\nif (val === 'previous_state' || val === 'current_state') {\n- $customoutputs.comparatorProperty.attr('disabled', 'disabled');\n+ $customoutputs.comparatorPropertyValue.attr('disabled', 'disabled');\n$customoutputs.comparatorType.removeAttr('disabled');\n$customoutputs.comparatorValue.removeAttr('disabled');\n}\nif (val === 'property') {\n- $customoutputs.comparatorProperty.removeAttr('disabled');\n+ $customoutputs.comparatorPropertyValue.removeAttr('disabled');\n$customoutputs.comparatorType.removeAttr('disabled');\n$customoutputs.comparatorValue.removeAttr('disabled');\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.js",
"new_path": "nodes/trigger-state/trigger-state.js",
"diff": "@@ -26,6 +26,7 @@ module.exports = function(RED) {\nthis.messageTimers = {};\n}\nonClose(removed) {\n+ super.onClose();\n// TODO: test this\nif (removed) {\nthis.debug('removing all message timers onClose and node was removed');\n@@ -36,6 +37,18 @@ module.exports = function(RED) {\n}\n}\n+ onInput({ message }) {\n+ const p = message.payload;\n+ if (p.entity_id && p.new_state && p.old_state) {\n+ const evt = {\n+ event_type: 'state_changed',\n+ entity_id: p.entity_id,\n+ event: p\n+ };\n+ this.onEntityStateChanged(evt);\n+ }\n+ }\n+\nasync getConstraintTargetData(constraint, triggerEvent) {\nlet targetData = { entityid: null, state: null };\n@@ -86,6 +99,9 @@ module.exports = function(RED) {\nconst { entity_id, event } = evt;\nconst { nodeConfig } = this;\n+ // The event listener will only fire off correct entity events, this is for testing with incoming message\n+ if (entity_id !== this.nodeConfig.entityid) return;\n+\nconst allComparatorResults = [];\nlet comparatorsAllMatches = true;\n@@ -130,7 +146,7 @@ module.exports = function(RED) {\nif (output.comparatorPropertyType !== 'always') {\nconst actualValue = this.utils.reach(output.comparatorPropertyValue, event);\n- comparatorMatched = this.getComparatorResult(output.comparatorType, output.comparatorPropertyValue, actualValue);\n+ comparatorMatched = this.getComparatorResult(output.comparatorType, output.comparatorValue, actualValue);\n}\nlet message = (output.messageType === 'default') ? msg : output.messageValue;\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | trigger-state: fix for removing custom output causing node-red wires to be mis-mapped |
748,240 | 07.02.2018 03:14:49 | 18,000 | 7615c2f211214260be8f70bfca4084eaf78f2389 | trigger-state: wip: custom outputs, client logging, typedinput, etc.. | [
{
"change_type": "MODIFY",
"old_path": "lib/base-node.js",
"new_path": "lib/base-node.js",
"diff": "@@ -2,6 +2,7 @@ const Joi = require('joi');\nconst merge = require('lodash.merge');\nconst selectn = require('selectn');\nconst dateFns = require('date-fns');\n+const util = require('util');\nconst utils = {\nselectn,\n@@ -12,8 +13,11 @@ const utils = {\n};\nconst DEFAULT_OPTIONS = {\n- debug: false,\n- config: {},\n+ config: {\n+ debugenabled: {},\n+ name: {},\n+ server: { isNode: true }\n+ },\ninput: {\ntopic: { messageProp: 'topic' },\npayload: { messageProp: 'payload' }\n@@ -58,6 +62,7 @@ class BaseNode {\nsend() { this.node.send(...arguments) }\nflashFlowHaltedStatus() {\n+ this.debugToClient('Flow halted');\nthis.flashStatus({\nstatusFlash: { fill: 'yellow', shape: 'dot' },\nstatusAfter: { fill: 'yellow', shape: 'dot', text: `${new Date().toISOString()}: halted flow` },\n@@ -101,11 +106,28 @@ class BaseNode {\nthis.node.status(opts);\n}\n+ // Hack to get around the fact that node-red only sends warn / error to the debug tab\n+ debugToClient(debugMsg) {\n+ if (!this.nodeConfig.debugenabled) return;\n+ for (let msg of arguments) {\n+ const debugMsgObj = {\n+ id: this.id,\n+ name: this.name || '',\n+ msg\n+ };\n+ this.RED.comms.publish('debug', debugMsgObj);\n+ }\n+ }\n+\ndebug() {\n- if (!this.options.debug) return;\n- console.log(`*****DEBUG: ${this.node.type}:${this.node.id}`, ...arguments);\n+ super.debug(...arguments);\n}\n+ // debug() {\n+ // if (!this.options.debug) return;\n+ // console.log(`*****DEBUG: ${this.node.type}:${this.node.id}`, ...arguments);\n+ // }\n+\n// Returns the evaluated path on this class instance\n// ex: myNode.reach('nodeConfig.server.events')\nreach(path) {\n@@ -157,7 +179,9 @@ const _internals = {\nconst _eventHandlers = {\npreOnInput(message) {\n+ this.debugToClient('Incoming Message', message);\nthis.debug('Incoming message: ', message);\n+\nif (this.options.debug) this.flashStatus();\ntry {\nconst parsedMessage = _internals.parseInputMessage.call(this, this.options.input, message);\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.html",
"new_path": "nodes/trigger-state/trigger-state.html",
"diff": "<!-- Entity ID Filter and Filter Type -->\n<div class=\"form-row\">\n<label for=\"node-input-entityid\"><i class=\"fa fa-tag\"></i> Entity ID</label>\n- <input type=\"text\" id=\"node-input-entityid\" placeholder=\"binary_sensor\" style=\"width: 50%;\" />\n+ <input type=\"text\" id=\"node-input-entityid\" placeholder=\"binary_sensor\" style=\"width: 70%;\" />\n</div>\n<!-- Add Constraint -->\n- <div class=\"form-row\" id=\"add-constraint-container\">\n+ <div class=\"form-row\" id=\"add-container\">\n+ <!-- -------------------------------------------------------------- -->\n+ <!-- Add Custom Constraints -->\n+ <!-- -------------------------------------------------------------- -->\n<h3>Add Constraints</h3>\n<div>\n<!-- Target Selection -->\n</select>\n<!-- Value -->\n- <input type=\"text\" id=\"constraint-comparator-value\" style=\"width: 62%\" />\n+ <input type=\"text\" id=\"constraint-comparator-value\" />\n</div>\n<!-- Add Constraint Button -->\n<ol id=\"output-list\"></ol>\n</div>\n+ <div class=\"form-row\">\n+ <label for=\"node-input-debugenabled\"><i class=\"fa fa-server\"></i> Debug Enabled</label>\n+ <input type=\"checkbox\" id=\"node-input-debugenabled\" />\n+ </div>\n+\n</script>\nname: { value: '' },\nserver: { value: '', type: 'server', required: true },\nentityid: { value: '', required: true },\n+ debugenabled: { value: false },\nconstraints: { value: [] },\noutputs: { value: 2 },\ncustomoutputs: { value: [] }\npaletteLabel: 'trigger: state',\nlabel: function() { return this.name || `trigger-state: ${this.entityid}` },\noneditprepare: function () {\n+ // Outputs List\n+ let NODE = this;\nconst NUM_DEFAULT_OUTPUTS = 2;\nconst $entityid = $('#node-input-entityid');\nconst $server = $('#node-input-server');\nconst $outputs = $('#node-input-outputs');\n+ const $accordionContainer = $('#add-container');\n+ const $constraints = {\n+ list: $('#constraint-list'),\n+ addBtn: $('#constraint-add-btn'),\n- const getRandomId = () => Math.random().toString(36).slice(2);\n+ targetType: $('#constraint-target-type'),\n+ targetValue: $('#constraint-target-value'),\n+ propertyType: $('#constraint-property-type'),\n+ propertyValue: $('#constraint-property-value'),\n+ comparatorType: $('#constraint-comparator-type'),\n+ comparatorValue: $('#constraint-comparator-value')\n+ };\n- $entityid.val(this.entityid);\n+ const $customoutputs = {\n+ list: $('#output-list'),\n+ addBtn: $('#output-add-btn'),\n- // New nodes, select first available home-assistant config node found\n- if (!this.server) {\n- let defaultServer;\n- RED.nodes.eachConfig(n => {\n- if (n.type === 'server' && !defaultServer) defaultServer = n.id;\n- });\n- if (defaultServer) $server.val(defaultServer);\n- }\n+ timerType: $('#output-timer-type'),\n+ timerValue: $('#output-timer-value'),\n+ timerUnit: $('#output-timer-unit'),\n+\n+ messageType: $('#output-message-type'),\n+ messageValue: $('#output-message-value'),\n+\n+ comparatorPropertyType: $('#output-comparator-property-type'),\n+ comparatorPropertyValue: $('#output-comparator-property-value'),\n+ comparatorType: $('#output-comparator-type'),\n+ comparatorValue: $('#output-comparator-value')\n+ };\n- const setupAutocomplete = (node) => {\n+ const utils = {\n+ getRandomId: () => Math.random().toString(36).slice(2),\n+ setupAutocomplete: () => {\nconst selectedServer = $server.val();\n// A home assistant server is selected in the node config\n- if (node.server || (selectedServer && selectedServer !== '_ADD_')) {\n+ if (NODE.server || (selectedServer && selectedServer !== '_ADD_')) {\n$.get('/homeassistant/entities').done((entities) => {\n- node.availableEntities = JSON.parse(entities);\n- $entityid.autocomplete({ source: node.availableEntities, minLength: 0 });\n+ NODE.availableEntities = JSON.parse(entities);\n+ $entityid.autocomplete({ source: NODE.availableEntities, minLength: 0 });\n})\n.fail((err) => RED.notify(err.responseText, 'error'));\n}\n+ },\n+ setDefaultServerSelection: function () {\n+ let defaultServer;\n+ RED.nodes.eachConfig(n => {\n+ if (n.type === 'server' && !defaultServer) defaultServer = n.id;\n+ });\n+ if (defaultServer) $server.val(defaultServer);\n+ }\n};\n- $server.change(() => setupAutocomplete(this));\n-\n// **************************\n// * Add Constraints\n// **************************\n- const $constraints = {\n- list: $('#constraint-list'),\n- container: $('#add-constraint-container'),\n- addBtn: $('#constraint-add-btn'),\n-\n- targetType: $('#constraint-target-type'),\n- targetValue: $('#constraint-target-value'),\n- propertyType: $('#constraint-property-type'),\n- propertyValue: $('#constraint-property-value'),\n- comparatorType: $('#constraint-comparator-type'),\n- comparatorValue: $('#constraint-comparator-value')\n- };\n-\n- $constraints.container.accordion({ active: false, collapsible: true, heightStyle: 'content' });\n-\n- // Constraint select menu change handlers\n- $constraints.targetType.on('change', function (e) {\n+ const constraintsHandler = {\n+ onTargetTypeChange: function(e) {\nconst val = e.target.value;\n(val === 'this_entity')\n? $constraints.targetValue.attr('disabled', 'disabled')\n: $constraints.targetValue.removeAttr('disabled')\n- });\n- $constraints.propertyType.on('change', function (e) {\n+ },\n+ onPropertyTypeChange: function(e) {\nconst val = e.target.value;\n(val === 'current_state' || val === 'previous_state')\n? $constraints.propertyValue.attr('disabled', 'disabled')\n: $constraints.propertyValue.removeAttr('disabled');\n- });\n- $constraints.comparatorType.on('change', function (e) {\n- const val = e.target.value;\n- console.log('comparator type changed to: ', val);\n- });\n- // TODO: Add debounced change handler for input that validates on keyup and marks field invalid, disable/enables add button\n- // TODO: Disabled add button initially\n-\n- // Constraint Add Button\n- $constraints.addBtn.on('click', function() {\n+ },\n+ onComparatorTypeChange: function(e) {\n+ const val = e.target.value; // Placeholder\n+ },\n+ onAddConstraintButton: function(e) {\nconst constraint = {\n- id: getRandomId(),\n+ id: utils.getRandomId(),\ntargetType: $constraints.targetType.val(),\ntargetValue: $constraints.targetValue.val(),\npropertyType: $constraints.propertyType.val(),\npropertyValue: $constraints.propertyValue.val(),\ncomparatorType: $constraints.comparatorType.val(),\n- comparatorValue: $constraints.comparatorValue.val()\n+ comparatorValueDatatype: $constraints.comparatorValue.typedInput('type'),\n+ comparatorValue: $constraints.comparatorValue.typedInput('value')\n};\nif (constraint.propertyType === 'current_state') constraint.propertyValue = 'new_state.state';\nif (constraint.propertyType === 'previous_state') constraint.propertyValue = 'old_state.state';\n+ if (constraint.comparatorType === 'includes' || constraint.comparatorType === 'does_not_include') {\n+ constraint.comparatorValueDatatype = 'list';\n+ }\n+\n$constraints.list.editableList('addItem', constraint);\n$constraints.targetValue.val('');\n- });\n-\n- // Constraints List\n- $constraints.list.editableList({\n- addButton: false,\n- height: 159,\n- sortable: true,\n- removable: true,\n- removeItem( data ) {\n- console.log('Item removed', data);\n},\n- addItem: function(row, index, data) {\n- console.log('Adding item data: ', data);\n+ onEditableListAdd: function(row, index, data) {\nconst $row = $(row);\n- const { targetType, targetValue, propertyType, propertyValue, comparatorType, comparatorValue } = data;\n+ const { targetType, targetValue, propertyType, propertyValue, comparatorType, comparatorValue, comparatorValueDatatype } = data;\nconst entityText = (targetType === 'this_entity') ? 'this entity' : targetValue;\n- const propertyText = (propertyType === 'property') ? propertyText : propertyType.replace('_', ' ');\n+ const propertyText = (propertyType === 'property') ? propertyValue : propertyType.replace('_', ' ');\nconst comparatorTypeText = comparatorType.replace('_', ' ');\nconst rowHtml = `\n- <strong>${entityText}:</strong> ${propertyText} ${comparatorTypeText} ${comparatorValue}\n+ <strong>${entityText}:</strong> ${propertyText} ${comparatorTypeText} (${comparatorValueDatatype}) ${comparatorValue}\n`;\n$row.html(rowHtml);\n}\n+ };\n+\n+ // Constraint select menu change handlers\n+ $constraints.targetType.on('change', constraintsHandler.onTargetTypeChange);\n+ $constraints.propertyType.on('change', constraintsHandler.onPropertyTypeChange);\n+ $constraints.comparatorType.on('change', constraintsHandler.onComparatorTypeChange);\n+\n+ $constraints.addBtn.on('click', constraintsHandler.onAddConstraintButton);\n+\n+ // Constraints List\n+ $constraints.list.editableList({\n+ addButton: false,\n+ height: 159,\n+ sortable: true,\n+ removable: true,\n+ addItem: constraintsHandler.onEditableListAdd\n});\n- // Add previous constraints to list\n- this.constraints.forEach(c => $constraints.list.editableList('addItem', c));\n+ $constraints.comparatorValue.typedInput({\n+ default: 'str',\n+ types: ['str', 'num', 'bool', 're' ]\n+ });\n+ $constraints.comparatorValue.typedInput('width', '100px');\n// **************************\n// * Add Custom Outputs\n// **************************\n- const $customoutputs = {\n- list: $('#output-list'),\n- addBtn: $('#output-add-btn'),\n-\n- timerType: $('#output-timer-type'),\n- timerValue: $('#output-timer-value'),\n- timerUnit: $('#output-timer-unit'),\n-\n- messageType: $('#output-message-type'),\n- messageValue: $('#output-message-value'),\n-\n- comparatorPropertyType: $('#output-comparator-property-type'),\n- comparatorPropertyValue: $('#output-comparator-property-value'),\n- comparatorType: $('#output-comparator-type'),\n- comparatorValue: $('#output-comparator-value')\n- };\n-\n- // Outputs Add Button\n- $customoutputs.addBtn.on('click', function() {\n+ const outputsHandler = {\n+ onAddButtonClicked: function() {\nconst output = {\n- outputId: getRandomId(),\n+ outputId: utils.getRandomId(),\ntimerType: $customoutputs.timerType.val(),\ntimerValue: $customoutputs.timerValue.val(),\ntimerUnit: $customoutputs.timerUnit.val(),\n// Removing an output and adding in same edit session means output\n// map needs to be adjusted, otherwise just increment count\n- debugger;\nif (isNaN(NODE.outputs)) {\n- // const maxOutput = Math.max(Object.keys(NODE.outputs));\n- NODE.outputs[getRandomId()] = 'abc';\n+ const maxOutput = Math.max(Object.keys(NODE.outputs));\n+ NODE.outputs[utils.getRandomId()] = maxOutput + 1;\n} else {\nNODE.outputs = parseInt(NODE.outputs) + 1;\n}\n- $outputs.val(isNaN(NODE.outputs) ? JSON.parse(NODE.outputs) : NODE.outputs);\n+ $outputs.val(isNaN(NODE.outputs) ? JSON.stringify(NODE.outputs) : NODE.outputs);\nif (output.comparatorPropertyType === 'current_state') output.comparatorPropertyValue = 'new_state.state';\nif (output.comparatorPropertyType === 'previous_state') output.comparatorPropertyValue = 'old_state.state';\n+ NODE.customoutputs.push(output);\n+\n$customoutputs.list.editableList('addItem', output);\n- });\n+ },\n+ onEditableListAdd: function(row, index, data) {\n+ const $row = $(row);\n+ const { comparatorType, comparatorValue } = data;\n+ const htmlData = JSON.stringify(data);\n- // Outputs List\n- let NODE = this;\n- $customoutputs.list.editableList({\n- addButton: false,\n- height: 159,\n- sortable: false,\n- removable: true,\n- removeItem( data ) {\n- console.log('Item removed', data);\n+ $row.html(htmlData);\n+ },\n+ onEditableListRemove: function ( data ) {\n// node-red uses a map of old output index to new output index to re-map\n// links between nodes. If new index is -1 then it was removed\n+\nlet customOutputRemovedIndex = NODE.customoutputs.indexOf(data);\nNODE.outputs = !(isNaN(NODE.outputs)) ? { 0: 0, 1: 1 } : NODE.outputs;\nNODE.outputs[customOutputRemovedIndex + NUM_DEFAULT_OUTPUTS] = -1;\n$outputs.val(JSON.stringify(NODE.outputs));\n},\n- addItem: function(row, index, data) {\n- console.log('Adding output data: ', data);\n- const $row = $(row);\n- const { comparatorType, comparatorValue } = data;\n- const htmlData = JSON.stringify(data);\n-\n- $row.html(htmlData);\n- }\n- });\n-\n- // Constraint select menu change handlers\n- $customoutputs.timerType.on('change', function (e) {\n+ onTimerTypeChange: function(e) {\nconst val = e.target.value;\nif (val === 'immediate') {\n$customoutputs.timerValue.attr('disabled', 'disabled')\n$customoutputs.timerValue.removeAttr('disabled')\n$customoutputs.timerUnit.removeAttr('disabled')\n}\n- });\n- $customoutputs.messageType.on('change', function (e) {\n+ },\n+ onMessageTypeChange: function(e) {\nconst val = e.target.value;\n(val === 'default')\n? $customoutputs.messageValue.attr('disabled', 'disabled')\n: $customoutputs.messageValue.removeAttr('disabled');\n- });\n- $customoutputs.comparatorPropertyType.on('change', function (e) {\n+ },\n+ comparatorPropertyTypeChange: function(e) {\nconst val = e.target.value;\nif (val === 'always') {\n$customoutputs.comparatorPropertyValue.attr('disabled', 'disabled');\n$customoutputs.comparatorType.removeAttr('disabled');\n$customoutputs.comparatorValue.removeAttr('disabled');\n}\n+ }\n+ }\n+ $customoutputs.list.editableList({\n+ addButton: false,\n+ height: 159,\n+ sortable: false,\n+ removable: true,\n+ removeItem: outputsHandler.onEditableListRemove,\n+ addItem: outputsHandler.onEditableListAdd\n});\n+ // Constraint select menu change handlers\n+ $customoutputs.timerType.on('change', outputsHandler.onTimerTypeChange);\n+ $customoutputs.messageType.on('change', outputsHandler.onMessageTypeChange);\n+ $customoutputs.comparatorPropertyType.on('change', outputsHandler.comparatorPropertyTypeChange);\n+\n+ $customoutputs.addBtn.on('click', outputsHandler.onAddButtonClicked);\n- // Add previous outputs to list\n- this.customoutputs.forEach(o => $customoutputs.list.editableList('addItem', o));\n+ // **************************\n+ // * General Init\n+ // **************************\n+ $accordionContainer.accordion({ active: false, collapsible: true, heightStyle: 'content' });\n+ $entityid.val(NODE.entityid);\n+ $server.change(() => utils.setupAutocomplete(this));\n+\n+ // New nodes, select first available home-assistant config node found\n+ if (!NODE.server) {\n+ utils.setDefaultServerSelection();\n+ } else {\n+ utils.setupAutocomplete();\n+ }\n+\n+ // Add previous constraints/outputs to editable lists\n+ NODE.constraints.forEach(c => $constraints.list.editableList('addItem', c));\n+ NODE.customoutputs.forEach(o => $customoutputs.list.editableList('addItem', o));\n},\noneditsave: function() {\nconst $constraintsList = $('#constraint-list');\nthis.customoutputs = nodeOutputs;\nthis.outputs = this.customoutputs.length + 2;\n- },\n- // oneditresize: function(size) {\n- // var rows = $(\"#dialog-form>div:not(.node-input-rule-container-row)\");\n- // var height = size.height;\n- // for (var i=0;i<rows.size();i++) {\n- // height -= $(rows[i]).outerHeight(true);\n- // }\n- // var editorRow = $(\"#dialog-form>div.node-input-rule-container-row\");\n- // height -= (parseInt(editorRow.css(\"marginTop\"))+parseInt(editorRow.css(\"marginBottom\")));\n- // $(\"#node-input-rule-container\").editableList('height',height);\n- // }\n+ }\n});\n</script>\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.js",
"new_path": "nodes/trigger-state/trigger-state.js",
"diff": "@@ -20,22 +20,25 @@ module.exports = function(RED) {\nclass TriggerState extends EventsNode {\nconstructor(nodeDefinition) {\nsuper(nodeDefinition, RED, nodeOptions);\n- const eventTopic = `ha_events:state_changed:${this.nodeConfig.entityid}`;\n+\n+ const eventTopic = this.eventTopic = `ha_events:state_changed:${this.nodeConfig.entityid}`;\nthis.addEventClientListener({ event: eventTopic, handler: this.onEntityStateChanged.bind(this) });\nthis.NUM_DEFAULT_MESSAGES = 2;\nthis.messageTimers = {};\n}\n+ onHaEventsOpen() {\n+ super.onHaEventsOpen();\n+ this.debugToClient(`connected, listening for ha events topic: ${this.eventTopic}`);\n+ }\nonClose(removed) {\nsuper.onClose();\n- // TODO: test this\n- if (removed) {\n+\nthis.debug('removing all message timers onClose and node was removed');\nObject.keys(this.messageTimers).forEach(k => {\nif (this.messageTimers[k]) clearTimeout(this.messageTimers[k]);\nthis.messageTimers[k] = null;\n});\n}\n- }\nonInput({ message }) {\nconst p = message.payload;\n@@ -45,6 +48,8 @@ module.exports = function(RED) {\nentity_id: p.entity_id,\nevent: p\n};\n+\n+ this.debugToClient('injecting \"fake\" ha event from input msg received: ', evt);\nthis.onEntityStateChanged(evt);\n}\n}\n@@ -74,33 +79,52 @@ module.exports = function(RED) {\nreturn targetData;\n}\n+ getCastValue(datatype, value) {\n+ if (!datatype) return value;\n+\n+ switch (datatype) {\n+ case 'num': return parseFloat(value);\n+ case 'str': return value + '';\n+ case 'bool': return !!value;\n+ case 're': return new RegExp(value);\n+ case 'list': return value.split(',');\n+ default: return value;\n+ }\n+ }\n+\n/* eslint-disable indent */\n- getComparatorResult(comparatorType, comparatorValue, actualValue) {\n+ getComparatorResult(comparatorType, comparatorValue, actualValue, comparatorValueDatatype) {\n+ const cValue = this.getCastValue(comparatorValueDatatype, comparatorValue);\n+\nswitch (comparatorType) {\ncase 'is':\n- return comparatorValue === actualValue;\ncase 'is_not':\n- return comparatorValue !== actualValue;\n- case 'greater_than':\n- return comparatorValue > actualValue;\n- case 'less_than':\n- return comparatorValue < actualValue;\n+ // Datatype might be num, bool, str, re (regular expression)\n+ const isMatch = (comparatorValueDatatype === 're') ? cValue.test(actualValue) : (cValue === actualValue);\n+ return (comparatorType === 'is') ? isMatch : !isMatch;\ncase 'includes':\ncase 'does_not_include':\n- const filterResults = comparatorValue.split(',').filter(cvalue => (cvalue === actualValue));\n- return (comparatorType === 'includes')\n- ? filterResults.length > 0\n- : filterResults.length < 1;\n+ const isIncluded = cValue.includes(actualValue);\n+ return (comparatorType === 'includes') ? isIncluded : !isIncluded;\n+ case 'greater_than':\n+ return actualValue > cValue;\n+ case 'less_than':\n+ return actualValue < cValue;\n}\n}\nasync onEntityStateChanged (evt) {\n+ this.debugToClient('received state_changed event', evt);\n+\ntry {\nconst { entity_id, event } = evt;\nconst { nodeConfig } = this;\n// The event listener will only fire off correct entity events, this is for testing with incoming message\n- if (entity_id !== this.nodeConfig.entityid) return;\n+ if (entity_id !== this.nodeConfig.entityid) {\n+ this.debugToClient(`incoming entity_id(${entity_id}) does not match configured entity_id: (${this.nodeConfig.entityid}), skipping event processing`);\n+ return;\n+ }\nconst allComparatorResults = [];\nlet comparatorsAllMatches = true;\n@@ -109,7 +133,11 @@ module.exports = function(RED) {\nfor (let constraint of nodeConfig.constraints) {\nconst constraintTarget = await this.getConstraintTargetData(constraint, event);\nconst actualValue = this.utils.reach(constraint.propertyValue, constraintTarget.state);\n- const comparatorResult = this.getComparatorResult(constraint.comparatorType, constraint.comparatorValue, actualValue);\n+ const comparatorResult = this.getComparatorResult(constraint.comparatorType, constraint.comparatorValue, actualValue, constraint.comparatorValueDatatype);\n+\n+ if (!comparatorResult) {\n+ this.debugToClient(`constraint comparator failed: entity \"${constraintTarget.entityid}\" property \"${constraint.propertyValue}\" with value ${actualValue} failed \"${constraint.comparatorType}\" check against (${constraint.comparatorValueDatatype}) ${constraint.comparatorValue}`);\n+ }\n// If all previous comparators were true and this comparator is true then all matched so far\ncomparatorsAllMatches = comparatorsAllMatches && comparatorResult;\n@@ -125,35 +153,36 @@ module.exports = function(RED) {\nlet outputs;\nif (!comparatorsAllMatches) {\n- this.debug(`one more more comparators failed to match constraints, flow halted as a result, failed results below: `);\n+ this.debugToClient('one more more comparators failed to match constraints, message will output on failed output');\n- const failedConstraints = allComparatorResults.filter(res => !res.comparatorResult)\n- .map(res => {\n- this.debug(`Failed Result: \"${res.constraintTarget.entityid}\" had value of \"${res.actualValue}\" which failed an \"${res.constraint.comparatorType}\" check against expected value \"${res.constraint.comparatorValue}\"`);\n- return res;\n- });\n+ const failedConstraints = allComparatorResults.filter(res => !res.comparatorResult);\nmsg.failedConstraints = failedConstraints;\noutputs = [null, msg];\n} else {\n+ this.debugToClient('all (if any) constraints passed checks');\noutputs = [msg, null];\n}\n- if (!this.nodeConfig.customoutputs.length) return this.send(outputs);\n+ // If constraints failed, or we have no custom outputs then we're done\n+ if (!comparatorsAllMatches || !this.nodeConfig.customoutputs.length) {\n+ this.debugToClient('done processing sending messages: ', outputs);\n+ return this.send(outputs);\n+ }\n// Map output to matched customoutputs\nconst customoutputMsgs = this.nodeConfig.customoutputs.reduce((acc, output, reduceIndex) => {\nlet comparatorMatched = true;\n-\n+ let actualValue;\nif (output.comparatorPropertyType !== 'always') {\n- const actualValue = this.utils.reach(output.comparatorPropertyValue, event);\n- comparatorMatched = this.getComparatorResult(output.comparatorType, output.comparatorValue, actualValue);\n+ actualValue = this.utils.reach(output.comparatorPropertyValue, event);\n+ comparatorMatched = this.getComparatorResult(output.comparatorType, output.comparatorValue, actualValue, output.comparatorValueDatatype);\n}\nlet message = (output.messageType === 'default') ? msg : output.messageValue;\n// If comparator did not matched no need to go further\nif (!comparatorMatched) {\n- this.debug('Skipping message, output comparator failed');\n+ this.debugToClient(`output comparator failed: property \"${output.comparatorPropertyValue}\" with value ${actualValue} failed \"${output.comparatorType}\" check against (${output.comparatorValueDatatype}) ${output.comparatorValue}`);\nacc.push(null);\nreturn acc;\n}\n@@ -161,27 +190,28 @@ module.exports = function(RED) {\n// If comparator matched and send immediate is set just assign message to output\nif (output.timerType === 'immediate') {\nacc.push(message);\n- this.debug('Adding immediate message');\n+ this.debugToClient(`output ${output.outputId}: adding \"immediate\" send of message: `);\n+ this.debugToClient(message);\nreturn acc;\n}\n+ // Get the timer ms value\n+ const timerDelayMs = output.timerValue * TIMER_MULTIPLIERS[output.timerUnit];\n+\n// If already timer scheduler for this output then clear it for re-setting\nif (this.messageTimers[output.outputId]) {\n- this.debug('Found already scheduled message, extending the message timeout');\n+ this.debugToClient(`output ${output.outputId}: found already scheduled message, clearing timer to reschedule`);\nclearTimeout(this.messageTimers[output.outputId]);\n}\n- // Get the timer ms value\n- const timerDelayMs = output.timerValue * TIMER_MULTIPLIERS[output.timerUnit];\n-\n// Create the message to send, all outputs leading to this one with null (dont send) values\nconst customOutputIndexWithDefaults = reduceIndex + this.NUM_DEFAULT_MESSAGES;\nconst scheduledMessage = (new Array(customOutputIndexWithDefaults + 1)).fill(null);\nscheduledMessage[customOutputIndexWithDefaults] = message;\n- this.debug('Created scheduledMessage: ', scheduledMessage);\n+ this.debugToClient(`output ${output.outputId}: scheduled message for send after ${timerDelayMs}ms, message contents: `, message);\nthis.messageTimers[output.outputId] = setTimeout(() => {\n- this.debug('Sending delayed message', scheduledMessage);\n+ this.debugToClient(`output ${output.outputId}: sending delayed message: `, scheduledMessage);\nthis.send(scheduledMessage);\ndelete this.messageTimers[output.outputId];\n}, timerDelayMs);\n@@ -192,7 +222,7 @@ module.exports = function(RED) {\n}, []);\noutputs = outputs.concat(customoutputMsgs);\n- this.debug('Sending default output messages and any matched custom outputs(if any)');\n+ this.debugToClient('done processing sending messages: ', outputs);\nthis.send(outputs);\n} catch (e) {\nthis.error(e);\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | trigger-state: wip: custom outputs, client logging, typedinput, etc.. |
748,240 | 07.02.2018 05:47:52 | 18,000 | 48f0115bc297882616b8197b083b2ed0b8ddeb74 | removed status flashing, added timers cancel, enable/disable to trigger-state node | [
{
"change_type": "MODIFY",
"old_path": "lib/base-node.js",
"new_path": "lib/base-node.js",
"diff": "@@ -61,43 +61,6 @@ class BaseNode {\nsend() { this.node.send(...arguments) }\n- flashFlowHaltedStatus() {\n- this.debugToClient('Flow halted');\n- this.flashStatus({\n- statusFlash: { fill: 'yellow', shape: 'dot' },\n- statusAfter: { fill: 'yellow', shape: 'dot', text: `${new Date().toISOString()}: halted flow` },\n- clearAfter: 5000\n- });\n- }\n-\n- flashStatus(flashOptions = {}) {\n- const flashOpts = Object.assign({}, { statusFlash: null, statusAfter: {}, clearAfter: 0 }, flashOptions);\n- this.statusClear();\n-\n- let hide = () => this.node.status({});\n- let show = (status) => this.node.status(status || { shape: 'dot', fill: 'grey' });\n-\n- let showing = false;\n- this.timersStatusFlash = setInterval(() => {\n- (showing) ? hide() : show(flashOpts.statusFlash);\n- showing = !showing;\n- }, 100);\n-\n- this.timersStatusFlashStop = setTimeout(() => {\n- clearInterval(this.timersStatusFlash);\n- show(flashOpts.statusAfter);\n- this.timersStatusClear = setTimeout(() => hide(), flashOpts.clearAfter);\n- }, 1000);\n- };\n-\n- // Cancel any timers associated with and blank out the status\n- statusClear() {\n- clearInterval(this.timersStatusFlash);\n- clearTimeout(this.timersStatusFlashStop);\n- clearTimeout(this.timersStatusClear);\n- this.node.status();\n- }\n-\nsetStatusError(msg) {\nthis.setStatus({ fill: 'red', shape: 'ring', text: msg });\n}\n@@ -182,7 +145,6 @@ const _eventHandlers = {\nthis.debugToClient('Incoming Message', message);\nthis.debug('Incoming message: ', message);\n- if (this.options.debug) this.flashStatus();\ntry {\nconst parsedMessage = _internals.parseInputMessage.call(this, this.options.input, message);\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/events-node.js",
"new_path": "lib/events-node.js",
"diff": "@@ -45,11 +45,19 @@ class EventsNode extends BaseNode {\nonHaEventsError(err) {\nif (err.message) this.error(err.message);\n}\n+ updateConnectionStatus() {\n+ this.setConnectionStatus(this.isConnected);\n+ }\nsetConnectionStatus(isConnected) {\n- (isConnected)\n- ? this.setStatus({ shape: 'dot', fill: 'green', text: 'connected' })\n- : this.setStatus({ shape: 'ring', fill: 'red', text: 'disconnected' });\n+ let connectionStatus = isConnected\n+ ? { shape: 'dot', fill: 'green', text: 'connected' }\n+ : { shape: 'ring', fill: 'red', text: 'disconnected' };\n+ if (this.hasOwnProperty('isenabled') && this.isenabled === false) {\n+ connectionStatus.text += '(DISABLED)';\n+ }\n+\n+ this.setStatus(connectionStatus);\n}\nget eventsClient() {\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/api_call-service/api_call-service.js",
"new_path": "nodes/api_call-service/api_call-service.js",
"diff": "@@ -46,7 +46,6 @@ module.exports = function(RED) {\n? JSON.stringify(data)\n: data;\n- this.flashStatus();\nthis.debug(`Calling Service: ${domain}:${service} -- ${data}`);\nreturn this.nodeConfig.server.api.callService(domain, service, data)\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/api_current-state/api_current-state.js",
"new_path": "nodes/api_current-state/api_current-state.js",
"diff": "@@ -41,8 +41,9 @@ module.exports = function(RED) {\nconst shouldHaltIfState = this.nodeConfig.halt_if && (currentState.state === this.nodeConfig.halt_if);\nif (shouldHaltIfState) {\n- this.debug(`Get current state: halting processing due to current state of ${entity_id} matches \"halt if state\" option`);\n- this.flashFlowHaltedStatus();\n+ const debugMsg = `Get current state: halting processing due to current state of ${entity_id} matches \"halt if state\" option`;\n+ this.debug(debugMsg);\n+ this.debugToClient(debugMsg);\nreturn null;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/server-events-all/server-events-all.js",
"new_path": "nodes/server-events-all/server-events-all.js",
"diff": "@@ -9,7 +9,6 @@ module.exports = function(RED) {\nonHaEventsAll(evt) {\nthis.send({ event_type: evt.event_type, topic: evt.event_type, payload: evt });\n- this.flashStatus();\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.js",
"new_path": "nodes/trigger-state/trigger-state.js",
"diff": "@@ -12,6 +12,7 @@ module.exports = function(RED) {\ndebug: true,\nconfig: {\nentityid: {},\n+ isenabled: {},\nconstraints: {},\ncustomoutputs: {}\n}\n@@ -32,8 +33,9 @@ module.exports = function(RED) {\n}\nonClose(removed) {\nsuper.onClose();\n-\n- this.debug('removing all message timers onClose and node was removed');\n+ this.clearAllTimers();\n+ }\n+ clearAllTimers() {\nObject.keys(this.messageTimers).forEach(k => {\nif (this.messageTimers[k]) clearTimeout(this.messageTimers[k]);\nthis.messageTimers[k] = null;\n@@ -41,7 +43,27 @@ module.exports = function(RED) {\n}\nonInput({ message }) {\n+ if (message === 'reset' || message.payload === 'reset') {\n+ this.debugToClient('canceling all timers due to incoming \"reset\" message');\n+ this.clearAllTimers();\n+ return;\n+ }\n+ // NOTE: Need to look at way to update node config via serverside, doesn't look like it's supported at all.\n+ if (message === 'enable' || message.payload === 'enable') {\n+ this.debugToClient('node set to enabled by incoming \"enable\" message');\n+ this.isenabled = true;\n+ this.updateConnectionStatus();\n+ return;\n+ }\n+ if (message === 'disable' || message.payload === 'disable') {\n+ this.debugToClient('node set to disabled by incoming \"disable\" message');\n+ this.isenabled = false;\n+ this.updateConnectionStatus();\n+ return;\n+ }\n+\nconst p = message.payload;\n+\nif (p.entity_id && p.new_state && p.old_state) {\nconst evt = {\nevent_type: 'state_changed',\n@@ -114,6 +136,11 @@ module.exports = function(RED) {\n}\nasync onEntityStateChanged (evt) {\n+ if (!this.isenabled) {\n+ this.debugToClient('node is currently disabled, ignoring received event: ', evt);\n+ return;\n+ }\n+\nthis.debugToClient('received state_changed event', evt);\ntry {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | removed status flashing, added timers cancel, enable/disable to trigger-state node |
748,240 | 07.02.2018 06:46:07 | 18,000 | a2ab630c5d14b1c3aa3e47608a723dce13b16e8b | Status fixes and extending timer if output constraint matches even if main constraints fail | [
{
"change_type": "MODIFY",
"old_path": "lib/base-node.js",
"new_path": "lib/base-node.js",
"diff": "@@ -53,6 +53,7 @@ class BaseNode {\nconst name = this.reach('nodeConfig.name');\nthis.debug(`instantiated node, name: ${name || 'undefined'}`);\n+ this.updateConnectionStatus();\n}\n// Subclasses should override these as hooks into common events\n@@ -69,6 +70,21 @@ class BaseNode {\nthis.node.status(opts);\n}\n+ updateConnectionStatus() {\n+ this.setConnectionStatus(this.isConnected);\n+ }\n+\n+ setConnectionStatus(isConnected) {\n+ let connectionStatus = isConnected\n+ ? { shape: 'dot', fill: 'green', text: 'connected' }\n+ : { shape: 'ring', fill: 'red', text: 'disconnected' };\n+ if (this.hasOwnProperty('isenabled') && this.isenabled === false) {\n+ connectionStatus.text += '(DISABLED)';\n+ }\n+\n+ this.setStatus(connectionStatus);\n+ }\n+\n// Hack to get around the fact that node-red only sends warn / error to the debug tab\ndebugToClient(debugMsg) {\nif (!this.nodeConfig.debugenabled) return;\n@@ -86,10 +102,13 @@ class BaseNode {\nsuper.debug(...arguments);\n}\n- // debug() {\n- // if (!this.options.debug) return;\n- // console.log(`*****DEBUG: ${this.node.type}:${this.node.id}`, ...arguments);\n- // }\n+ get eventsClient() {\n+ return this.reach('nodeConfig.server.events');\n+ }\n+\n+ get isConnected() {\n+ return this.eventsClient && this.eventsClient.connected;\n+ }\n// Returns the evaluated path on this class instance\n// ex: myNode.reach('nodeConfig.server.events')\n@@ -154,7 +173,6 @@ const _eventHandlers = {\n});\n} catch (e) {\nif (e && e.isJoi) {\n- this.setStatusError('Validation Error, flow halted');\nthis.node.warn(e.message);\nreturn this.send(null);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/events-node.js",
"new_path": "lib/events-node.js",
"diff": "@@ -36,37 +36,15 @@ class EventsNode extends BaseNode {\n}\nonHaEventsClose() {\n- this.setConnectionStatus(false);\n+ this.updateConnectionStatus();\n}\nonHaEventsOpen() {\n- this.setConnectionStatus(true);\n+ this.updateConnectionStatus();\n}\nonHaEventsError(err) {\nif (err.message) this.error(err.message);\n}\n- updateConnectionStatus() {\n- this.setConnectionStatus(this.isConnected);\n- }\n-\n- setConnectionStatus(isConnected) {\n- let connectionStatus = isConnected\n- ? { shape: 'dot', fill: 'green', text: 'connected' }\n- : { shape: 'ring', fill: 'red', text: 'disconnected' };\n- if (this.hasOwnProperty('isenabled') && this.isenabled === false) {\n- connectionStatus.text += '(DISABLED)';\n- }\n-\n- this.setStatus(connectionStatus);\n- }\n-\n- get eventsClient() {\n- return this.reach('nodeConfig.server.events');\n- }\n-\n- get isConnected() {\n- return this.eventsClient && this.eventsClient.connected;\n- }\n};\nmodule.exports = EventsNode;\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.js",
"new_path": "nodes/trigger-state/trigger-state.js",
"diff": "@@ -90,7 +90,7 @@ module.exports = function(RED) {\n} else {\nconst state = await this.nodeConfig.server.homeAssistant.getStates(targetData.entityid);\ntargetData.state = {\n- new_state: state[targetData.entityid]\n+ new_state: state\n};\n}\n} catch (e) {\n@@ -136,7 +136,7 @@ module.exports = function(RED) {\n}\nasync onEntityStateChanged (evt) {\n- if (!this.isenabled) {\n+ if (this.isenabled === false) {\nthis.debugToClient('node is currently disabled, ignoring received event: ', evt);\nreturn;\n}\n@@ -180,7 +180,7 @@ module.exports = function(RED) {\nlet outputs;\nif (!comparatorsAllMatches) {\n- this.debugToClient('one more more comparators failed to match constraints, message will output on failed output');\n+ this.debugToClient('one more more comparators failed to match constraints, message will send on failed output');\nconst failedConstraints = allComparatorResults.filter(res => !res.comparatorResult);\nmsg.failedConstraints = failedConstraints;\n@@ -190,8 +190,8 @@ module.exports = function(RED) {\noutputs = [msg, null];\n}\n- // If constraints failed, or we have no custom outputs then we're done\n- if (!comparatorsAllMatches || !this.nodeConfig.customoutputs.length) {\n+ // If constraints failed and we have no custom outputs then we're done\n+ if (!comparatorsAllMatches && !this.nodeConfig.customoutputs.length) {\nthis.debugToClient('done processing sending messages: ', outputs);\nreturn this.send(outputs);\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Status fixes and extending timer if output constraint matches even if main constraints fail |
748,240 | 07.02.2018 08:42:26 | 18,000 | bac244c4485ebcf642c41f26bab01d4544ae3563 | added db store to persist certain states across restart | [
{
"change_type": "MODIFY",
"old_path": "lib/base-node.js",
"new_path": "lib/base-node.js",
"diff": "@@ -2,7 +2,9 @@ const Joi = require('joi');\nconst merge = require('lodash.merge');\nconst selectn = require('selectn');\nconst dateFns = require('date-fns');\n-const util = require('util');\n+\n+const low = require('lowdb');\n+const FileAsync = require('lowdb/adapters/FileAsync');\nconst utils = {\nselectn,\n@@ -24,6 +26,8 @@ const DEFAULT_OPTIONS = {\n}\n};\n+let DB;\n+\nclass BaseNode {\nconstructor(nodeDefinition, RED, options = {}) {\n// Need to bring in NodeRed dependency and properly extend Node class, or just make this class a node handler\n@@ -56,15 +60,49 @@ class BaseNode {\nthis.updateConnectionStatus();\n}\n+ async getDb() {\n+ try {\n+ if (DB) return DB;\n+\n+ let dbLocation = this.RED.settings.get('userDir');\n+ if (!dbLocation) throw new Error('Could not find userDir to use for database store');\n+ dbLocation += '/node-red-contrib-home-assistant.json';\n+\n+ const adapter = new FileAsync(dbLocation);\n+ DB = await low(adapter);\n+ DB.defaults({ nodes: {} });\n+ return DB;\n+ } catch (e) { throw e }\n+ }\n+\n// Subclasses should override these as hooks into common events\nonClose(removed) {}\nonInput() {}\n+ get nodeDbId() {\n+ return `nodes.${this.id.replace('.', '_')}`;\n+ }\n+ // namespaces data by nodeid to the lowdb store\n+ async saveNodeData(key, value) {\n+ if (!this.id || !key) throw new Error('cannot persist data to db without id and key');\n+ const path = `${this.nodeDbId}.${key}`;\n+ const db = await this.getDb();\n+ return db.set(path, value).write();\n+ }\n+ async getNodeData(key) {\n+ if (!this.id) throw new Error('cannot get node data from db without id');\n+ const db = await this.getDb();\n+ let path = `${this.nodeDbId}`;\n+ if (key) path = path + `.${key}`;\n- send() { this.node.send(...arguments) }\n-\n- setStatusError(msg) {\n- this.setStatus({ fill: 'red', shape: 'ring', text: msg });\n+ return db.get(path).value();\n}\n+ async removeNodeData() {\n+ if (!this.id) throw new Error('cannot get node data from db without id');\n+ const db = await this.getDb();\n+ return db.remove(this.nodeDbId).write();\n+ }\n+\n+ send() { this.node.send(...arguments) }\nsetStatus(opts = { shape: 'dot', fill: 'blue', text: '' }) {\nthis.node.status(opts);\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.js",
"new_path": "nodes/trigger-state/trigger-state.js",
"diff": "@@ -26,14 +26,30 @@ module.exports = function(RED) {\nthis.addEventClientListener({ event: eventTopic, handler: this.onEntityStateChanged.bind(this) });\nthis.NUM_DEFAULT_MESSAGES = 2;\nthis.messageTimers = {};\n+\n+ this.loadPersistedData();\n+ }\n+ async loadPersistedData() {\n+ try {\n+ const data = await this.getNodeData();\n+ if (data && data.hasOwnProperty('isenabled')) {\n+ this.isenabled = data.isenabled;\n+ this.updateConnectionStatus();\n+ }\n+ } catch (e) {\n+ this.error(e.message);\n+ }\n}\nonHaEventsOpen() {\nsuper.onHaEventsOpen();\nthis.debugToClient(`connected, listening for ha events topic: ${this.eventTopic}`);\n}\n- onClose(removed) {\n+ async onClose(removed) {\nsuper.onClose();\nthis.clearAllTimers();\n+ if (removed) {\n+ await this.removeNodeData();\n+ }\n}\nclearAllTimers() {\nObject.keys(this.messageTimers).forEach(k => {\n@@ -52,12 +68,15 @@ module.exports = function(RED) {\nif (message === 'enable' || message.payload === 'enable') {\nthis.debugToClient('node set to enabled by incoming \"enable\" message');\nthis.isenabled = true;\n+ this.saveNodeData('isenabled', true);\nthis.updateConnectionStatus();\nreturn;\n}\nif (message === 'disable' || message.payload === 'disable') {\nthis.debugToClient('node set to disabled by incoming \"disable\" message');\nthis.isenabled = false;\n+ this.clearAllTimers();\n+ this.saveNodeData('isenabled', false);\nthis.updateConnectionStatus();\nreturn;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "package-lock.json",
"new_path": "package-lock.json",
"diff": "\"is-promise\": {\n\"version\": \"2.1.0\",\n\"resolved\": \"https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz\",\n- \"integrity\": \"sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=\",\n- \"dev\": true\n+ \"integrity\": \"sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=\"\n},\n\"is-resolvable\": {\n\"version\": \"1.1.0\",\n\"resolved\": \"https://registry.npmjs.org/lodash.toarray/-/lodash.toarray-4.4.0.tgz\",\n\"integrity\": \"sha1-JMS/zWsvuji/0FlNsRedjptlZWE=\"\n},\n+ \"lowdb\": {\n+ \"version\": \"1.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/lowdb/-/lowdb-1.0.0.tgz\",\n+ \"integrity\": \"sha512-2+x8esE/Wb9SQ1F9IHaYWfsC9FIecLOPrK4g17FGEayjUWH172H6nwicRovGvSE2CPZouc2MCIqCI7h9d+GftQ==\",\n+ \"requires\": {\n+ \"graceful-fs\": \"4.1.11\",\n+ \"is-promise\": \"2.1.0\",\n+ \"lodash\": \"4.17.4\",\n+ \"pify\": \"3.0.0\",\n+ \"steno\": \"0.4.4\"\n+ },\n+ \"dependencies\": {\n+ \"pify\": {\n+ \"version\": \"3.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/pify/-/pify-3.0.0.tgz\",\n+ \"integrity\": \"sha1-5aSs0sEB/fPZpNB/DbxNtJ3SgXY=\"\n+ }\n+ }\n+ },\n\"lru-cache\": {\n\"version\": \"4.1.1\",\n\"resolved\": \"https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.1.tgz\",\n\"tweetnacl\": \"0.14.5\"\n}\n},\n+ \"steno\": {\n+ \"version\": \"0.4.4\",\n+ \"resolved\": \"https://registry.npmjs.org/steno/-/steno-0.4.4.tgz\",\n+ \"integrity\": \"sha1-BxEFvfwobmYVwEA8J+nXtdy4Vcs=\",\n+ \"requires\": {\n+ \"graceful-fs\": \"4.1.11\"\n+ }\n+ },\n\"stream-transform\": {\n\"version\": \"0.2.2\",\n\"resolved\": \"https://registry.npmjs.org/stream-transform/-/stream-transform-0.2.2.tgz\",\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"is-string\": \"^1.0.4\",\n\"joi\": \"^13.1.1\",\n\"lodash.merge\": \"^4.6.0\",\n+ \"lowdb\": \"^1.0.0\",\n\"node-home-assistant\": \"^0.2.0\",\n\"selectn\": \"^1.1.2\"\n},\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | added db store to persist certain states across restart |
748,240 | 07.02.2018 10:23:42 | 18,000 | 6c236b2ee4a4bb0347969062955d79caf5acf8f5 | trigger-state node: added scheduled message indicator | [
{
"change_type": "MODIFY",
"old_path": "lib/base-node.js",
"new_path": "lib/base-node.js",
"diff": "@@ -108,11 +108,11 @@ class BaseNode {\nthis.node.status(opts);\n}\n- updateConnectionStatus() {\n- this.setConnectionStatus(this.isConnected);\n+ updateConnectionStatus(additionalText) {\n+ this.setConnectionStatus(this.isConnected, additionalText);\n}\n- setConnectionStatus(isConnected) {\n+ setConnectionStatus(isConnected, additionalText) {\nlet connectionStatus = isConnected\n? { shape: 'dot', fill: 'green', text: 'connected' }\n: { shape: 'ring', fill: 'red', text: 'disconnected' };\n@@ -120,6 +120,8 @@ class BaseNode {\nconnectionStatus.text += '(DISABLED)';\n}\n+ if (additionalText) connectionStatus.text += ` ${additionalText}`;\n+\nthis.setStatus(connectionStatus);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.js",
"new_path": "nodes/trigger-state/trigger-state.js",
"diff": "@@ -40,6 +40,18 @@ module.exports = function(RED) {\nthis.error(e.message);\n}\n}\n+ updateConnectionStatus() {\n+ if (!this.messageTimers) return super.updateConnectionStatus();\n+ const msgKeys = Object.keys(this.messageTimers);\n+ const additionalText = msgKeys.length > 0 ? `(${msgKeys.length} msgs scheduled)` : null;\n+ super.updateConnectionStatus(additionalText);\n+ }\n+ clearAllTimers() {\n+ Object.keys(this.messageTimers).forEach(k => {\n+ if (this.messageTimers[k]) clearTimeout(this.messageTimers[k]);\n+ this.messageTimers[k] = null;\n+ });\n+ }\nonHaEventsOpen() {\nsuper.onHaEventsOpen();\nthis.debugToClient(`connected, listening for ha events topic: ${this.eventTopic}`);\n@@ -51,13 +63,6 @@ module.exports = function(RED) {\nawait this.removeNodeData();\n}\n}\n- clearAllTimers() {\n- Object.keys(this.messageTimers).forEach(k => {\n- if (this.messageTimers[k]) clearTimeout(this.messageTimers[k]);\n- this.messageTimers[k] = null;\n- });\n- }\n-\nonInput({ message }) {\nif (message === 'reset' || message.payload === 'reset') {\nthis.debugToClient('canceling all timers due to incoming \"reset\" message');\n@@ -120,6 +125,7 @@ module.exports = function(RED) {\nreturn targetData;\n}\n+ /* eslint-disable indent */\ngetCastValue(datatype, value) {\nif (!datatype) return value;\n@@ -260,10 +266,12 @@ module.exports = function(RED) {\nthis.debugToClient(`output ${output.outputId}: sending delayed message: `, scheduledMessage);\nthis.send(scheduledMessage);\ndelete this.messageTimers[output.outputId];\n+ this.updateConnectionStatus();\n}, timerDelayMs);\n// Since the message was scheduled push null val to current message output list\nacc.push(null);\n+ this.updateConnectionStatus();\nreturn acc;\n}, []);\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | trigger-state node: added scheduled message indicator |
748,240 | 07.02.2018 10:46:22 | 18,000 | 2b7b752714c12163a52c3bddd71cd06d5fa60119 | New nodes added will now automatically default to the first found home assistant configuration for the 'server' node value if not set | [
{
"change_type": "MODIFY",
"old_path": "nodes/api_call-service/api_call-service.html",
"new_path": "nodes/api_call-service/api_call-service.html",
"diff": "} }\n},\noneditprepare: function () {\n+ const NODE = this;\n+ const $server = $('#node-input-server');\n+\nconst $domainField = $('#service_domain');\nconst $serviceField = $('#service');\n+\nconst $serviceDataDiv = $('#service-data-desc');\nconst $serviceDescDiv = $('.service-description', $serviceDataDiv);\nconst $serviceDataTableBody = $('tbody', $serviceDataDiv);\n$serviceField.val(node.service);\nsetServicesAndDomains(node);\n+ const utils = {\n+ setDefaultServerSelection: function () {\n+ let defaultServer;\n+ RED.nodes.eachConfig(n => {\n+ if (n.type === 'server' && !defaultServer) defaultServer = n.id;\n+ });\n+ if (defaultServer) $server.val(defaultServer);\n+ }\n+ };\n+\n+ if (!NODE.server) {\n+ utils.setDefaultServerSelection();\n+ }\n+\n// Calls the custom api backend defined in the config-server.js node\n// TODO: Not sure how this works with node-red if auth is enabled\nfunction setServicesAndDomains(node) {\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/api_current-state/api_current-state.html",
"new_path": "nodes/api_current-state/api_current-state.html",
"diff": "}\n},\noneditprepare: function () {\n-\nconst $entityIdField = $('#entity_id');\n$entityIdField.val(this.entity_id);\n+ const NODE = this;\n+ const $server = $('#node-input-server');\n+ const utils = {\n+ setDefaultServerSelection: function () {\n+ let defaultServer;\n+ RED.nodes.eachConfig(n => {\n+ if (n.type === 'server' && !defaultServer) defaultServer = n.id;\n+ });\n+ if (defaultServer) $server.val(defaultServer);\n+ }\n+ };\n+\n+ if (!NODE.server) {\n+ utils.setDefaultServerSelection();\n+ }\n+\n// Check that proper config is set\nconst config = RED.nodes.node($('#node-input-server').val());\nconst isConfigValid = (config && config.valid);\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/api_get-history/api_get-history.html",
"new_path": "nodes/api_get-history/api_get-history.html",
"diff": "return `${startdate.toLocaleDateString()} ${startdate.toLocaleTimeString()}`;\n}\nreturn 'get history';\n+ },\n+ oneditprepare: function() {\n+ const NODE = this;\n+ const $server = $('#node-input-server');\n+ const utils = {\n+ setDefaultServerSelection: function () {\n+ let defaultServer;\n+ RED.nodes.eachConfig(n => {\n+ if (n.type === 'server' && !defaultServer) defaultServer = n.id;\n+ });\n+ if (defaultServer) $server.val(defaultServer);\n+ }\n+ };\n+\n+ if (!NODE.server) {\n+ utils.setDefaultServerSelection();\n+ }\n}\n});\n</script>\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/api_render-template/api_render-template.html",
"new_path": "nodes/api_render-template/api_render-template.html",
"diff": "<script type=\"text/javascript\">\n+(function() {\nRED.nodes.registerType('api-render-template', {\ncategory: 'home_assistant',\ncolor: '#52C0F2',\nlabel: function() { return this.name || `template: ${this.template || ''}` },\noneditprepare: function () {\n+ const NODE = this;\n+ const $server = $('#node-input-server');\n+ const utils = {\n+ setDefaultServerSelection: function () {\n+ let defaultServer;\n+ RED.nodes.eachConfig(n => {\n+ if (n.type === 'server' && !defaultServer) defaultServer = n.id;\n+ });\n+ if (defaultServer) $server.val(defaultServer);\n+ }\n+ };\n+\n+ if (!NODE.server) {\n+ utils.setDefaultServerSelection();\n+ }\n+\n$inputTemplate = $(\"#node-input-template\");\n// NOTE: Copypasta from node-red/nodes/core/template node\ndelete this.editor;\n}\n});\n+})();\n</script>\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/server-events-all/server-events-all.html",
"new_path": "nodes/server-events-all/server-events-all.html",
"diff": "outputs: 1,\nicon: \"arrow-right-bold.png\",\npaletteLabel: 'events: all',\n- label: function() { return this.name || `events_all: ${this.eventtypefilter}` }\n+ label: function() { return this.name || `events_all: ${this.eventtypefilter}` },\n+ oneditprepare: function() {\n+ const NODE = this;\n+ const $server = $('#node-input-server');\n+ const utils = {\n+ setDefaultServerSelection: function () {\n+ let defaultServer;\n+ RED.nodes.eachConfig(n => {\n+ if (n.type === 'server' && !defaultServer) defaultServer = n.id;\n+ });\n+ if (defaultServer) $server.val(defaultServer);\n+ }\n+ };\n+\n+ if (!NODE.server) {\n+ utils.setDefaultServerSelection();\n+ }\n+ }\n});\n</script>\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/server-events-state-changed/server-events-state-changed.html",
"new_path": "nodes/server-events-state-changed/server-events-state-changed.html",
"diff": "$entityidfiltertype.val(this.entityidfiltertype);\n$entityidfilter.val(this.entityidfilter);\n+ const NODE = this;\n+ const utils = {\n+ setDefaultServerSelection: function () {\n+ let defaultServer;\n+ RED.nodes.eachConfig(n => {\n+ if (n.type === 'server' && !defaultServer) defaultServer = n.id;\n+ });\n+ if (defaultServer) $server.val(defaultServer);\n+ }\n+ };\n+\n+ if (!NODE.server) {\n+ utils.setDefaultServerSelection();\n+ }\n+\nconst setupAutocomplete = (node) => {\nconst selectedServer = $server.val();\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | New nodes added will now automatically default to the first found home assistant configuration for the 'server' node value if not set |
748,240 | 07.02.2018 11:41:07 | 18,000 | 66cd103f2c0203b9fc429574d173f8243d9f86f1 | api-call-service node: should now properly merge incoming payload.data values with the config value | [
{
"change_type": "MODIFY",
"old_path": "nodes/api_call-service/api_call-service.html",
"new_path": "nodes/api_call-service/api_call-service.html",
"diff": "<script type=\"text/javascript\">\n- // TODO: Look for autocomplete modules to allow a select drop down (with autocomplete)\n- // the options would be populated by the api query of services on the server node\nRED.nodes.registerType('api-call-service', {\ncategory: 'home_assistant',\ncolor: '#52C0F2',\nalign: 'right',\npaletteLabel: 'call service',\nlabel: function() { return this.name || `svc: ${this.service_domain}:${this.service}`; },\n- // NOTE: 'domain' seems to be a nodered 'reserved' word as we get an error about enter not being a function\n- // when trying to be used as a default below.\ndefaults: {\nname: { value: '' },\nserver: { value: '', type: 'server', required: true },\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/api_call-service/api_call-service.js",
"new_path": "nodes/api_call-service/api_call-service.js",
"diff": "@@ -7,26 +7,9 @@ module.exports = function(RED) {\nconfig: {\nservice_domain: {},\nservice: {},\n- data: {}, // TODO: If string cast to object\n+ data: {},\nname: {},\nserver: { isNode: true }\n- },\n- input: {\n- domain: {\n- messageProp: 'payload.domain',\n- configProp: 'service_domain', // Will be used if value not found on message,\n- validation: { haltOnFail: true, schema: Joi.string().min(1).required() }\n- },\n- service: {\n- messageProp: 'payload.service',\n- configProp: 'service',\n- validation: { haltOnFail: true, schema: Joi.string().min(1).required() }\n- },\n- data: { // TODO: If found on payload then merge with config object if exists\n- messageProp: 'payload.data',\n- configProp: 'data',\n- validation: { schema: Joi.object({}) }\n- }\n}\n};\n@@ -34,21 +17,50 @@ module.exports = function(RED) {\nconstructor(nodeDefinition) {\nsuper(nodeDefinition, RED, nodeOptions);\n}\n+ isObjectLike (v) {\n+ return (v != null) && (typeof v == 'object'); // eslint-disable-line\n+ }\n+ // Disable connection status for api node\n+ setConnectionStatus() {}\n+\n+ onInput({ message }) {\n+ let { service_domain, service, data } = this.nodeConfig;\n+ if (data && !this.isObjectLike(data)) {\n+ try {\n+ data = JSON.parse(data);\n+ } catch (e) {}\n+ }\n- onInput({ parsedMessage, message }) {\n- let { domain, service, data } = parsedMessage;\n- domain = domain.value;\n- service = service.value;\n- data = data.value;\n+ const pDomain = this.utils.reach('payload.domain', message);\n+ const pService = this.utils.reach('payload.service', message);\n+ const pData = this.utils.reach('payload.data', message);\n- const isObjectLike = (v) => (v != null) && (typeof value == 'object'); // eslint-disable-line\n- data = isObjectLike(data)\n- ? JSON.stringify(data)\n- : data;\n- this.debug(`Calling Service: ${domain}:${service} -- ${data}`);\n+ // domain and service are strings, if they exist in payload overwrite any config value\n+ const apiDomain = pDomain || service_domain;\n+ const apiService = pService || service;\n+ if (!apiDomain) throw new Error('call service node is missing api \"domain\" property, not found in config or payload');\n+ if (!apiService) throw new Error('call service node is missing api \"service\" property, not found in config or payload');\n+\n+ let apiData;\n+ // api data should be an object or falsey, if an object then attempt to merge with config value if also an object\n+ if (this.isObjectLike(pData)) {\n+ if (this.isObjectLike(data)) {\n+ apiData = this.utils.merge({}, data, pData);\n+ } else {\n+ apiData = pData;\n+ }\n+ // Not an object, but maybe \"something\"\n+ } else if (pData) {\n+ apiData = pData;\n+ } else {\n+ apiData = null;\n+ }\n+\n+ apiData = (apiData && this.isObjectLike(apiData)) ? JSON.stringify(apiData) : null;\n+ this.debugToClient(`Calling Service: ${apiDomain}:${apiService} -- ${apiData}`);\n- return this.nodeConfig.server.api.callService(domain, service, data)\n+ return this.nodeConfig.server.api.callService(apiDomain, apiService, apiData)\n.catch(err => {\nthis.warn('Error calling service, home assistant api error', err);\nthis.error('Error calling service, home assistant api error', message);\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | api-call-service node: should now properly merge incoming payload.data values with the config value |
748,240 | 07.02.2018 11:51:14 | 18,000 | 9e9e085c931eb2eb7909b9aa8babcbb1893945ed | trigger-state: custom output messages are now sent as objects if able to be parsed, previously was always strings | [
{
"change_type": "MODIFY",
"old_path": "nodes/api_call-service/api_call-service.js",
"new_path": "nodes/api_call-service/api_call-service.js",
"diff": "-const Joi = require('joi');\nconst BaseNode = require('../../lib/base-node');\nmodule.exports = function(RED) {\n@@ -35,7 +34,6 @@ module.exports = function(RED) {\nconst pService = this.utils.reach('payload.service', message);\nconst pData = this.utils.reach('payload.data', message);\n-\n// domain and service are strings, if they exist in payload overwrite any config value\nconst apiDomain = pDomain || service_domain;\nconst apiService = pService || service;\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.js",
"new_path": "nodes/trigger-state/trigger-state.js",
"diff": "@@ -230,7 +230,16 @@ module.exports = function(RED) {\ncomparatorMatched = this.getComparatorResult(output.comparatorType, output.comparatorValue, actualValue, output.comparatorValueDatatype);\n}\n- let message = (output.messageType === 'default') ? msg : output.messageValue;\n+ let message;\n+ if (output.messageType === 'default') {\n+ message = msg;\n+ } else {\n+ try {\n+ message = JSON.parse(output.messageValue);\n+ } catch (e) {\n+ message = output.messageValue;\n+ }\n+ }\n// If comparator did not matched no need to go further\nif (!comparatorMatched) {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | trigger-state: custom output messages are now sent as objects if able to be parsed, previously was always strings |
748,240 | 09.02.2018 01:25:45 | 18,000 | 59a586be0d296a1388aa4497991543ad88bf943b | wip: timed task serialization and restore | [
{
"change_type": "MODIFY",
"old_path": ".eslintrc.js",
"new_path": ".eslintrc.js",
"diff": "@@ -3,7 +3,7 @@ module.exports = {\nextends: 'standard',\nplugins: ['html'],\nparserOptions: { sourceType: 'module' },\n- env: { browser: true, node: true },\n+ env: { browser: true, node: true, mocha: true },\nglobals: {\n'__THEME': true\n},\n"
},
{
"change_type": "MODIFY",
"old_path": ".vscode/launch.json",
"new_path": ".vscode/launch.json",
"diff": "\"restart\": true,\n\"address\": \"localhost\",\n\"port\": 9123,\n- \"trace\": true,\n+ \"trace\": false,\n+\n+ \"skipFiles\": [\n+ \"<node_internals>/**/*.js\"\n+ ]\n+ },\n+ {\n+ \"name\": \"Attach Local: test\",\n+ \"type\": \"node\",\n+ \"request\": \"attach\",\n+ \"timeout\": 20000,\n+ \"restart\": true,\n+ \"address\": \"localhost\",\n+ \"port\": 9124,\n+ \"trace\": false,\n\"skipFiles\": [\n\"<node_internals>/**/*.js\"\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "__tests__/lib/timed-task.spec.js",
"diff": "+const test = require('tape');\n+const TimedTask = require('../../lib/timed-task');\n+\n+const NOW = 0;\n+\n+TimedTask.prototype.getNow = () => NOW;\n+\n+const options = () => ({\n+ id: 'my timed task',\n+ runsIn: 1,\n+ task: () => '1',\n+ onStart: () => '2',\n+ onComplete: () => '3',\n+ onCancel: () => '4',\n+ onFailed: (e) => '5'\n+});\n+\n+test('TimedTask: should instantiate', function(t) {\n+ const opts = options();\n+ const tt = new TimedTask(opts);\n+ t.equal(tt.id, opts.id, 'ids should work');\n+ t.equal(tt.runsAt, NOW + opts.runsIn, 'runsAt should be calculated');\n+ t.equal(typeof tt.task, 'function');\n+ t.end();\n+});\n+\n+test('TimedTask: should run task', function(t) {\n+ const opts = options();\n+ const onDone = () => t.end();\n+ opts.task = () => (t.pass('task called when scheduled'), onDone()); // eslint-disable-line\n+ new TimedTask(opts); // eslint-disable-line\n+});\n+\n+test('TimedTask: should call onStart and onComplete', function(t) {\n+ const opts = options();\n+\n+ const onDone = () => t.end();\n+ opts.onStart = () => t.pass('onStart called');\n+ opts.onComplete = () => (t.pass('on complete called'), onDone()); // eslint-disable-line\n+\n+ new TimedTask(opts); // eslint-disable-line\n+});\n+\n+test('TimedTask: should serialize', function(t) {\n+ const tt = new TimedTask(options());\n+ const str = tt.serialize();\n+ const expectedStr = `{\"id\":\"my timed task\",\"runsAt\":1,\"task\":() => '1',\"onStart\":() => '2',\"onComplete\":() => '3',\"onCancel\":() => '4',\"onFailed\":(e) => '5'}`;\n+ t.equal(str, expectedStr, 'serialized string is correct');\n+ t.end();\n+});\n+\n+test('TimedTask: should deserialize', function(t) {\n+ const opts = options();\n+ const tt = new TimedTask(opts);\n+ const str = tt.serialize();\n+ const timedTask = TimedTask.createFromSerialized(str);\n+\n+ t.equals(timedTask.id, opts.id, 'deserialized id is equal');\n+ t.equals(typeof timedTask.task, 'function', 'task function is deserialized correctly');\n+ t.end();\n+});\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "lib/timed-task.js",
"diff": "+const serialize = require('serialize-javascript');\n+\n+class TimedTask {\n+ constructor(o) {\n+ this.id = o.id;\n+ this.task = o.task;\n+ this.onStart = o.onStart;\n+ this.onComplete = o.onComplete;\n+ this.onCancel = o.onCancel;\n+ this.onFailed = o.onFailed;\n+\n+ const now = this.getNow();\n+ if (o.runsAt && (o.runsAt <= now)) throw new Error('Cannot schedule a task which is set to run in the past');\n+\n+ let runsIn = (o.runsAt)\n+ ? o.runsAt - now\n+ : o.runsIn;\n+\n+ this.schedule(runsIn);\n+ }\n+\n+ schedule(runsInMs) {\n+ this.cancel();\n+ this.scheduledAt = this.getNow();\n+ this.runsAt = this.scheduledAt + runsInMs;\n+ this.timer = setTimeout(this.start.bind(this), runsInMs);\n+ }\n+\n+ getNow() {\n+ return Date.now();\n+ }\n+\n+ cancel() {\n+ if (this.timer) {\n+ if (typeof this.onCancel === 'function') this.onCancel();\n+ clearTimeout(this.timer);\n+ ['timer', 'scheduledAt', 'runsAt'].forEach(k => (this[k] = null));\n+ }\n+ }\n+\n+ getRunsAtDate() {\n+ return new Date(this.runsAt);\n+ }\n+\n+ async start() {\n+ if (typeof this.onStart === 'function') this.onStart();\n+ try {\n+ await this.task();\n+ this.onComplete();\n+ } catch (e) {\n+ if (typeof this.onFailed === 'function') {\n+ this.cancel();\n+ this.onFailed(e);\n+ } else { throw e }\n+ }\n+ }\n+ static create(o) {\n+ return new TimedTask(o);\n+ }\n+\n+ static createFromSerialized(str) {\n+ const taskObj = eval('(' + str + ')'); // eslint-disable-line\n+ return new TimedTask(taskObj);\n+ }\n+\n+ serialize() {\n+ return serialize(this);\n+ }\n+\n+ // Called by stringify with serialize\n+ toJSON() {\n+ const { id, runsAt, task, onStart, onComplete, onCancel, onFailed } = this;\n+ return { id, runsAt, task, onStart, onComplete, onCancel, onFailed };\n+ }\n+}\n+\n+module.exports = TimedTask;\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.html",
"new_path": "nodes/trigger-state/trigger-state.html",
"diff": "<input type=\"text\" id=\"node-input-entityid\" placeholder=\"binary_sensor\" style=\"width: 70%;\" />\n</div>\n- <!-- Add Constraint -->\n- <div class=\"form-row\" id=\"add-container\">\n<!-- -------------------------------------------------------------- -->\n<!-- Add Custom Constraints -->\n<!-- -------------------------------------------------------------- -->\n+ <div class=\"form-row\" id=\"add-constraint-container\">\n<h3>Add Constraints</h3>\n<div>\n<!-- Target Selection -->\n<!-- Add Constraint Button -->\n<button id=\"constraint-add-btn\" style=\"width: 100%\">Add Constraint</button>\n</div>\n+ </div>\n+\n+ <!-- Constraints List -->\n+ <div class=\"form-row\">\n+ <ol id=\"constraint-list\"></ol>\n+ </div>\n<!-- -------------------------------------------------------------- -->\n<!-- Add Custom Outputs -->\n<!-- -------------------------------------------------------------- -->\n+ <div class=\"form-row\" id=\"add-output-container\">\n<h3>Add Outputs</h3>\n<div>\n<div class=\"form-row\">\n</div>\n</div>\n- <!-- Constraints List -->\n- <div class=\"form-row\">\n- <h6>Constraints</h6>\n- <ol id=\"constraint-list\"></ol>\n- </div>\n-\n- <!-- Constraints List -->\n+ <!-- Output List -->\n<div class=\"form-row\">\n- <h6>Custom Outputs</h6>\n<ol id=\"output-list\"></ol>\n</div>\n<div class=\"form-row\">\n- <label for=\"node-input-debugenabled\"><i class=\"fa fa-server\"></i> Debug Enabled</label>\n+ <label for=\"node-input-debugenabled\"><i class=\"fa fa-server\"></i> Debug</label>\n<input type=\"checkbox\" id=\"node-input-debugenabled\" />\n</div>\nentityid: { value: '', required: true },\ndebugenabled: { value: false },\nconstraints: { value: [] },\n+ constraintsmustmatch: { value: 'all' },\noutputs: { value: 2 },\ncustomoutputs: { value: [] }\n},\nconst $entityid = $('#node-input-entityid');\nconst $server = $('#node-input-server');\nconst $outputs = $('#node-input-outputs');\n- const $accordionContainer = $('#add-container');\n+ const $accordionContraint = $('#add-constraint-container');\n+ const $accordionOutput = $('#add-output-container');\nconst $constraints = {\nlist: $('#constraint-list'),\nconst $row = $(row);\nconst { targetType, targetValue, propertyType, propertyValue, comparatorType, comparatorValue, comparatorValueDatatype } = data;\n- const entityText = (targetType === 'this_entity') ? 'this entity' : targetValue;\n+ const entityText = (targetType === 'this_entity') ? '<strong>This entities</strong>' : `Entity ID <strong>${targetValue}</strong>`;\nconst propertyText = (propertyType === 'property') ? propertyValue : propertyType.replace('_', ' ');\nconst comparatorTypeText = comparatorType.replace('_', ' ');\n+ const comparatorText = `${comparatorTypeText} <strong>${comparatorValue}</strong> (${comparatorValueDatatype})`;\n- const rowHtml = `\n- <strong>${entityText}:</strong> ${propertyText} ${comparatorTypeText} (${comparatorValueDatatype}) ${comparatorValue}\n- `;\n-\n+ const rowHtml = `${entityText} ${propertyText} ${comparatorText}`;\n$row.html(rowHtml);\n}\n};\n$customoutputs.list.editableList('addItem', output);\n},\n- onEditableListAdd: function(row, index, data) {\n+ onEditableListAdd: function(row, index, d) {\nconst $row = $(row);\n- const { comparatorType, comparatorValue } = data;\n- const htmlData = JSON.stringify(data);\n- $row.html(htmlData);\n+ const typeText = (d.timerType === 'immediate')\n+ ? 'Immediate'\n+ : 'Delayed';\n+\n+ const messageText = (d.messageType === 'default')\n+ ? 'default message'\n+ : d.messageValue;\n+\n+ const sendWhenText = (d.comparatorPropertyType === 'always')\n+ ? 'always'\n+ : `${d.comparatorPropertyValue} ${d.comparatorType.replace('_', '')} ${d.comparatorValue}`\n+\n+ const sendAfterText = (d.timerType === 'immediate')\n+ ? 'immediately'\n+ : `${d.timerValue + d.timerUnit.substring(0,3)}`;\n+\n+ const html = `Send <strong>${messageText}</strong>, if <strong>${sendWhenText}</strong>, after <strong>${sendAfterText}</strong>`;\n+\n+ $row.html(html);\n},\nonEditableListRemove: function ( data ) {\n// node-red uses a map of old output index to new output index to re-map\n// **************************\n// * General Init\n// **************************\n- $accordionContainer.accordion({ active: false, collapsible: true, heightStyle: 'content' });\n+ $accordionContraint.accordion({ active: true, collapsible: true, heightStyle: 'content' });\n+ $accordionOutput.accordion({ active: false, collapsible: true, heightStyle: 'content' });\n+\n$entityid.val(NODE.entityid);\n$server.change(() => utils.setupAutocomplete(this));\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.js",
"new_path": "nodes/trigger-state/trigger-state.js",
"diff": "@@ -69,7 +69,7 @@ module.exports = function(RED) {\nthis.clearAllTimers();\nreturn;\n}\n- // NOTE: Need to look at way to update node config via serverside, doesn't look like it's supported at all.\n+\nif (message === 'enable' || message.payload === 'enable') {\nthis.debugToClient('node set to enabled by incoming \"enable\" message');\nthis.isenabled = true;\n"
},
{
"change_type": "MODIFY",
"old_path": "package-lock.json",
"new_path": "package-lock.json",
"diff": "\"resolved\": \"https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz\",\n\"integrity\": \"sha1-9lNNFRSCabIDUue+4m9QH5oZEpA=\"\n},\n+ \"deep-equal\": {\n+ \"version\": \"1.0.1\",\n+ \"resolved\": \"https://registry.npmjs.org/deep-equal/-/deep-equal-1.0.1.tgz\",\n+ \"integrity\": \"sha1-9dJgKStmDghO/0zbyfCK0yR0SLU=\",\n+ \"dev\": true\n+ },\n\"deep-is\": {\n\"version\": \"0.1.3\",\n\"resolved\": \"https://registry.npmjs.org/deep-is/-/deep-is-0.1.3.tgz\",\n\"clone\": \"1.0.3\"\n}\n},\n+ \"define-properties\": {\n+ \"version\": \"1.1.2\",\n+ \"resolved\": \"https://registry.npmjs.org/define-properties/-/define-properties-1.1.2.tgz\",\n+ \"integrity\": \"sha1-g6c/L+pWmJj7c3GTyPhzyvbUXJQ=\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"foreach\": \"2.0.5\",\n+ \"object-keys\": \"1.0.11\"\n+ }\n+ },\n+ \"defined\": {\n+ \"version\": \"1.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/defined/-/defined-1.0.0.tgz\",\n+ \"integrity\": \"sha1-yY2bzvdWdBiOEQlpFRGZ45sfppM=\",\n+ \"dev\": true\n+ },\n\"del\": {\n\"version\": \"2.2.2\",\n\"resolved\": \"https://registry.npmjs.org/del/-/del-2.2.2.tgz\",\n\"x256\": \"0.0.2\"\n}\n},\n+ \"duplexer3\": {\n+ \"version\": \"0.1.4\",\n+ \"resolved\": \"https://registry.npmjs.org/duplexer3/-/duplexer3-0.1.4.tgz\",\n+ \"integrity\": \"sha1-7gHdHKwO08vH/b6jfcCo8c4ALOI=\",\n+ \"dev\": true\n+ },\n\"ecc-jsbn\": {\n\"version\": \"0.1.1\",\n\"resolved\": \"https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.1.tgz\",\n\"is-arrayish\": \"0.2.1\"\n}\n},\n+ \"es-abstract\": {\n+ \"version\": \"1.10.0\",\n+ \"resolved\": \"https://registry.npmjs.org/es-abstract/-/es-abstract-1.10.0.tgz\",\n+ \"integrity\": \"sha512-/uh/DhdqIOSkAWifU+8nG78vlQxdLckUdI/sPgy0VhuXi2qJ7T8czBmqIYtLQVpCIFYafChnsRsB5pyb1JdmCQ==\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"es-to-primitive\": \"1.1.1\",\n+ \"function-bind\": \"1.1.1\",\n+ \"has\": \"1.0.1\",\n+ \"is-callable\": \"1.1.3\",\n+ \"is-regex\": \"1.0.4\"\n+ }\n+ },\n+ \"es-to-primitive\": {\n+ \"version\": \"1.1.1\",\n+ \"resolved\": \"https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.1.1.tgz\",\n+ \"integrity\": \"sha1-RTVSSKiJeQNLZ5Lhm7gfK3l13Q0=\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"is-callable\": \"1.1.3\",\n+ \"is-date-object\": \"1.0.1\",\n+ \"is-symbol\": \"1.0.1\"\n+ }\n+ },\n\"escape-string-regexp\": {\n\"version\": \"1.0.5\",\n\"resolved\": \"https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz\",\n}\n}\n},\n+ \"events-to-array\": {\n+ \"version\": \"1.1.2\",\n+ \"resolved\": \"https://registry.npmjs.org/events-to-array/-/events-to-array-1.1.2.tgz\",\n+ \"integrity\": \"sha1-LUH1Y+H+QA7Uli/hpNXGp1Od9/Y=\",\n+ \"dev\": true\n+ },\n\"eventsource\": {\n\"version\": \"1.0.5\",\n\"resolved\": \"https://registry.npmjs.org/eventsource/-/eventsource-1.0.5.tgz\",\n}\n}\n},\n+ \"for-each\": {\n+ \"version\": \"0.3.2\",\n+ \"resolved\": \"https://registry.npmjs.org/for-each/-/for-each-0.3.2.tgz\",\n+ \"integrity\": \"sha1-LEBFC5NI6X8oEyJZO6lnBLmr1NQ=\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"is-function\": \"1.0.1\"\n+ }\n+ },\n\"for-in\": {\n\"version\": \"1.0.2\",\n\"resolved\": \"https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz\",\n\"for-in\": \"1.0.2\"\n}\n},\n+ \"foreach\": {\n+ \"version\": \"2.0.5\",\n+ \"resolved\": \"https://registry.npmjs.org/foreach/-/foreach-2.0.5.tgz\",\n+ \"integrity\": \"sha1-C+4AUBiusmDQo6865ljdATbsG5k=\",\n+ \"dev\": true\n+ },\n\"forever-agent\": {\n\"version\": \"0.6.1\",\n\"resolved\": \"https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz\",\n\"resolved\": \"https://registry.npmjs.org/here/-/here-0.0.2.tgz\",\n\"integrity\": \"sha1-acGvPwISHz2HiOAuhNyLOQXXEZU=\"\n},\n+ \"hirestime\": {\n+ \"version\": \"3.2.1\",\n+ \"resolved\": \"https://registry.npmjs.org/hirestime/-/hirestime-3.2.1.tgz\",\n+ \"integrity\": \"sha512-VoXZ1Wz2lII6KZid7ByyeoW1TheD/Hiu6r9TjWWFUM2O3tddeRlj2/yGP63bZiIizHXW336eW0KNUiD6wngzSw==\",\n+ \"dev\": true\n+ },\n\"hoek\": {\n\"version\": \"5.0.2\",\n\"resolved\": \"https://registry.npmjs.org/hoek/-/hoek-5.0.2.tgz\",\n\"resolved\": \"https://registry.npmjs.org/invert-kv/-/invert-kv-1.0.0.tgz\",\n\"integrity\": \"sha1-EEqOSqym09jNFXqO+L+rLXo//bY=\"\n},\n+ \"irregular-plurals\": {\n+ \"version\": \"1.4.0\",\n+ \"resolved\": \"https://registry.npmjs.org/irregular-plurals/-/irregular-plurals-1.4.0.tgz\",\n+ \"integrity\": \"sha1-LKmwM2UREYVUEvFr5dd8YqRYp2Y=\",\n+ \"dev\": true\n+ },\n\"is-arrayish\": {\n\"version\": \"0.2.1\",\n\"resolved\": \"https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz\",\n\"builtin-modules\": \"1.1.1\"\n}\n},\n+ \"is-callable\": {\n+ \"version\": \"1.1.3\",\n+ \"resolved\": \"https://registry.npmjs.org/is-callable/-/is-callable-1.1.3.tgz\",\n+ \"integrity\": \"sha1-hut1OSgF3cM69xySoO7fdO52BLI=\",\n+ \"dev\": true\n+ },\n+ \"is-date-object\": {\n+ \"version\": \"1.0.1\",\n+ \"resolved\": \"https://registry.npmjs.org/is-date-object/-/is-date-object-1.0.1.tgz\",\n+ \"integrity\": \"sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY=\",\n+ \"dev\": true\n+ },\n\"is-extendable\": {\n\"version\": \"1.0.1\",\n\"resolved\": \"https://registry.npmjs.org/is-extendable/-/is-extendable-1.0.1.tgz\",\n\"resolved\": \"https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz\",\n\"integrity\": \"sha1-o7MKXE8ZkYMWeqq5O+764937ZU8=\"\n},\n+ \"is-function\": {\n+ \"version\": \"1.0.1\",\n+ \"resolved\": \"https://registry.npmjs.org/is-function/-/is-function-1.0.1.tgz\",\n+ \"integrity\": \"sha1-Es+5i2W1fdPRk6MSH19uL0N2ArU=\",\n+ \"dev\": true\n+ },\n\"is-path-cwd\": {\n\"version\": \"1.0.0\",\n\"resolved\": \"https://registry.npmjs.org/is-path-cwd/-/is-path-cwd-1.0.0.tgz\",\n\"resolved\": \"https://registry.npmjs.org/is-promise/-/is-promise-2.1.0.tgz\",\n\"integrity\": \"sha1-eaKp7OfwlugPNtKy87wWwf9L8/o=\"\n},\n+ \"is-regex\": {\n+ \"version\": \"1.0.4\",\n+ \"resolved\": \"https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz\",\n+ \"integrity\": \"sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"has\": \"1.0.1\"\n+ }\n+ },\n\"is-resolvable\": {\n\"version\": \"1.1.0\",\n\"resolved\": \"https://registry.npmjs.org/is-resolvable/-/is-resolvable-1.1.0.tgz\",\n\"resolved\": \"https://registry.npmjs.org/is-string/-/is-string-1.0.4.tgz\",\n\"integrity\": \"sha1-zDqbaYV9Yh6WNyWiTK7shzuCbmQ=\"\n},\n+ \"is-symbol\": {\n+ \"version\": \"1.0.1\",\n+ \"resolved\": \"https://registry.npmjs.org/is-symbol/-/is-symbol-1.0.1.tgz\",\n+ \"integrity\": \"sha1-PMWfAAJRlLarLjjbrmaJJWtmBXI=\",\n+ \"dev\": true\n+ },\n\"is-typedarray\": {\n\"version\": \"1.0.0\",\n\"resolved\": \"https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz\",\n\"integrity\": \"sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=\",\n\"dev\": true\n},\n+ \"minipass\": {\n+ \"version\": \"2.2.1\",\n+ \"resolved\": \"https://registry.npmjs.org/minipass/-/minipass-2.2.1.tgz\",\n+ \"integrity\": \"sha512-u1aUllxPJUI07cOqzR7reGmQxmCqlH88uIIsf6XZFEWgw7gXKpJdR+5R9Y3KEDmWYkdIz9wXZs3C0jOPxejk/Q==\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"yallist\": \"3.0.2\"\n+ },\n+ \"dependencies\": {\n+ \"yallist\": {\n+ \"version\": \"3.0.2\",\n+ \"resolved\": \"https://registry.npmjs.org/yallist/-/yallist-3.0.2.tgz\",\n+ \"integrity\": \"sha1-hFK0u36Dx8GI2AQcGoN8dz1ti7k=\",\n+ \"dev\": true\n+ }\n+ }\n+ },\n\"mixin-object\": {\n\"version\": \"3.0.0\",\n\"resolved\": \"https://registry.npmjs.org/mixin-object/-/mixin-object-3.0.0.tgz\",\n\"integrity\": \"sha512-smRWXzkvxw72VquyZ0wggySl7PFUtoDhvhpdwgESXxUrH7vVhhp9asfup1+rVLrhsl7L45Ee1Q/l5R2Ul4MwUg==\",\n\"dev\": true\n},\n+ \"object-inspect\": {\n+ \"version\": \"1.3.0\",\n+ \"resolved\": \"https://registry.npmjs.org/object-inspect/-/object-inspect-1.3.0.tgz\",\n+ \"integrity\": \"sha512-OHHnLgLNXpM++GnJRyyhbr2bwl3pPVm4YvaraHrRvDt/N3r+s/gDVHciA7EJBTkijKXj61ssgSAikq1fb0IBRg==\",\n+ \"dev\": true\n+ },\n+ \"object-keys\": {\n+ \"version\": \"1.0.11\",\n+ \"resolved\": \"https://registry.npmjs.org/object-keys/-/object-keys-1.0.11.tgz\",\n+ \"integrity\": \"sha1-xUYBd4rVYPEULODgG8yotW0TQm0=\",\n+ \"dev\": true\n+ },\n\"object-merge\": {\n\"version\": \"2.5.1\",\n\"resolved\": \"https://registry.npmjs.org/object-merge/-/object-merge-2.5.1.tgz\",\n\"error-ex\": \"1.3.1\"\n}\n},\n+ \"parse-ms\": {\n+ \"version\": \"1.0.1\",\n+ \"resolved\": \"https://registry.npmjs.org/parse-ms/-/parse-ms-1.0.1.tgz\",\n+ \"integrity\": \"sha1-VjRtR0nXjyNDDKDHE4UK75GqNh0=\",\n+ \"dev\": true\n+ },\n\"path-exists\": {\n\"version\": \"2.1.0\",\n\"resolved\": \"https://registry.npmjs.org/path-exists/-/path-exists-2.1.0.tgz\",\n\"find-up\": \"1.1.2\"\n}\n},\n+ \"plur\": {\n+ \"version\": \"2.1.2\",\n+ \"resolved\": \"https://registry.npmjs.org/plur/-/plur-2.1.2.tgz\",\n+ \"integrity\": \"sha1-dIJFLBoPUI4+NE6uwxLJHCncZVo=\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"irregular-plurals\": \"1.4.0\"\n+ }\n+ },\n\"pluralize\": {\n\"version\": \"7.0.0\",\n\"resolved\": \"https://registry.npmjs.org/pluralize/-/pluralize-7.0.0.tgz\",\n\"integrity\": \"sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ=\",\n\"dev\": true\n},\n+ \"pretty-ms\": {\n+ \"version\": \"3.1.0\",\n+ \"resolved\": \"https://registry.npmjs.org/pretty-ms/-/pretty-ms-3.1.0.tgz\",\n+ \"integrity\": \"sha1-6crJx2v27lL+lC3ZxsQhMVOxKIE=\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"parse-ms\": \"1.0.1\",\n+ \"plur\": \"2.1.2\"\n+ }\n+ },\n\"process-nextick-args\": {\n\"version\": \"1.0.7\",\n\"resolved\": \"https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-1.0.7.tgz\",\n\"signal-exit\": \"3.0.2\"\n}\n},\n+ \"resumer\": {\n+ \"version\": \"0.0.0\",\n+ \"resolved\": \"https://registry.npmjs.org/resumer/-/resumer-0.0.0.tgz\",\n+ \"integrity\": \"sha1-8ej0YeQGS6Oegq883CqMiT0HZ1k=\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"through\": \"2.3.8\"\n+ }\n+ },\n\"rimraf\": {\n\"version\": \"2.6.2\",\n\"resolved\": \"https://registry.npmjs.org/rimraf/-/rimraf-2.6.2.tgz\",\n\"resolved\": \"https://registry.npmjs.org/semver/-/semver-5.5.0.tgz\",\n\"integrity\": \"sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA==\"\n},\n+ \"serialize-javascript\": {\n+ \"version\": \"1.4.0\",\n+ \"resolved\": \"https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-1.4.0.tgz\",\n+ \"integrity\": \"sha1-fJWFFNtqwkQ6irwGLcn3iGp/YAU=\"\n+ },\n\"set-blocking\": {\n\"version\": \"2.0.0\",\n\"resolved\": \"https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz\",\n\"strip-ansi\": \"4.0.0\"\n}\n},\n+ \"string.prototype.trim\": {\n+ \"version\": \"1.1.2\",\n+ \"resolved\": \"https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.1.2.tgz\",\n+ \"integrity\": \"sha1-0E3iyJ4Tf019IG8Ia17S+ua+jOo=\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"define-properties\": \"1.1.2\",\n+ \"es-abstract\": \"1.10.0\",\n+ \"function-bind\": \"1.1.1\"\n+ }\n+ },\n\"string_decoder\": {\n\"version\": \"1.0.3\",\n\"resolved\": \"https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz\",\n\"string-width\": \"2.1.1\"\n}\n},\n+ \"tap-min\": {\n+ \"version\": \"1.2.2\",\n+ \"resolved\": \"https://registry.npmjs.org/tap-min/-/tap-min-1.2.2.tgz\",\n+ \"integrity\": \"sha512-R18JOoRHA4AXITwTrf8pPC4SfgO2usLM22pW8BBEPOWv3AOHbxarNN90Otygp4ChQ1oXd4u4vVp/FlH5pKMykg==\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"chalk\": \"2.3.0\",\n+ \"duplexer3\": \"0.1.4\",\n+ \"hirestime\": \"3.2.1\",\n+ \"pretty-ms\": \"3.1.0\",\n+ \"readable-stream\": \"2.3.3\",\n+ \"tap-parser\": \"6.0.1\"\n+ }\n+ },\n+ \"tap-parser\": {\n+ \"version\": \"6.0.1\",\n+ \"resolved\": \"https://registry.npmjs.org/tap-parser/-/tap-parser-6.0.1.tgz\",\n+ \"integrity\": \"sha512-1H9S4sE0etZqr0Ox3d5eCai5xrIk1zbR4pXxuNXAWo8PtoZDGsj2qrsOM1qaAW9JhwDgfAhllWaqCnysf4uVBg==\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"events-to-array\": \"1.1.2\",\n+ \"js-yaml\": \"3.10.0\",\n+ \"minipass\": \"2.2.1\"\n+ }\n+ },\n+ \"tape\": {\n+ \"version\": \"4.8.0\",\n+ \"resolved\": \"https://registry.npmjs.org/tape/-/tape-4.8.0.tgz\",\n+ \"integrity\": \"sha512-TWILfEnvO7I8mFe35d98F6T5fbLaEtbFTG/lxWvid8qDfFTxt19EBijWmB4j3+Hoh5TfHE2faWs73ua+EphuBA==\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"deep-equal\": \"1.0.1\",\n+ \"defined\": \"1.0.0\",\n+ \"for-each\": \"0.3.2\",\n+ \"function-bind\": \"1.1.1\",\n+ \"glob\": \"7.1.2\",\n+ \"has\": \"1.0.1\",\n+ \"inherits\": \"2.0.3\",\n+ \"minimist\": \"1.2.0\",\n+ \"object-inspect\": \"1.3.0\",\n+ \"resolve\": \"1.4.0\",\n+ \"resumer\": \"0.0.0\",\n+ \"string.prototype.trim\": \"1.1.2\",\n+ \"through\": \"2.3.8\"\n+ },\n+ \"dependencies\": {\n+ \"minimist\": {\n+ \"version\": \"1.2.0\",\n+ \"resolved\": \"https://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz\",\n+ \"integrity\": \"sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=\",\n+ \"dev\": true\n+ },\n+ \"resolve\": {\n+ \"version\": \"1.4.0\",\n+ \"resolved\": \"https://registry.npmjs.org/resolve/-/resolve-1.4.0.tgz\",\n+ \"integrity\": \"sha512-aW7sVKPufyHqOmyyLzg/J+8606v5nevBgaliIlV7nUpVMsDnoBGV/cbSLNjZAg9q0Cfd/+easKVKQ8vOu8fn1Q==\",\n+ \"dev\": true,\n+ \"requires\": {\n+ \"path-parse\": \"1.0.5\"\n+ }\n+ }\n+ }\n+ },\n\"term-canvas\": {\n\"version\": \"0.0.5\",\n\"resolved\": \"https://registry.npmjs.org/term-canvas/-/term-canvas-0.0.5.tgz\",\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"url\": \"https://github.com/AYapejian/node-red-contrib-home-assistant/issues\"\n},\n\"scripts\": {\n+ \"test\": \"tape __tests__/**/*.spec.js | tap-min\",\n+ \"test:debug\": \"node --inspect-brk=0.0.0.0:9124 node_modules/.bin/tape __tests__/**/*.spec.js\",\n+ \"test:watch\": \"nodemon -w __tests__/ -w lib/ -w nodes/ --exec 'node node_modules/.bin/tape __tests__/**/*.spec.js'\",\n\"dev\": \"npm run docker:up\",\n\"dev:clean\": \"npm run docker:down\",\n\"docker:up\": \"npm run docker -- up --build --abort-on-container-exit --remove-orphans\",\n\"lodash.merge\": \"^4.6.0\",\n\"lowdb\": \"^1.0.0\",\n\"node-home-assistant\": \"^0.2.0\",\n- \"selectn\": \"^1.1.2\"\n+ \"selectn\": \"^1.1.2\",\n+ \"serialize-javascript\": \"^1.4.0\"\n},\n\"devDependencies\": {\n\"eslint\": \"^4.8.0\",\n\"eslint-plugin-import\": \"^2.7.0\",\n\"eslint-plugin-node\": \"^5.2.0\",\n\"eslint-plugin-promise\": \"^3.5.0\",\n- \"eslint-plugin-standard\": \"^3.0.1\"\n+ \"eslint-plugin-standard\": \"^3.0.1\",\n+ \"tap-min\": \"^1.2.2\",\n+ \"tape\": \"^4.8.0\"\n}\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | wip: timed task serialization and restore |
748,240 | 09.02.2018 01:27:45 | 18,000 | 38ad159e230806dd18d490d837c1d4a03a5aa912 | pull dev-master node-home-assistant while testing | [
{
"change_type": "MODIFY",
"old_path": "package-lock.json",
"new_path": "package-lock.json",
"diff": "}\n},\n\"node-home-assistant\": {\n- \"version\": \"0.2.0\",\n- \"resolved\": \"https://registry.npmjs.org/node-home-assistant/-/node-home-assistant-0.2.0.tgz\",\n- \"integrity\": \"sha512-iaTVuWvmWKVgF4nsq/jlkGbFcYqieZg6SgCPRPzgQUQhS2dODz/la/iN8J0V9vBsA9yAw6lB3AvvoMeSwvWwyw==\",\n+ \"version\": \"github:AYapejian/node-home-assistant#9938ac3b7dddc445cad60c8da8e6330aa48ea7f2\",\n\"requires\": {\n\"axios\": \"0.17.1\",\n\"blessed\": \"0.1.81\",\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"joi\": \"^13.1.1\",\n\"lodash.merge\": \"^4.6.0\",\n\"lowdb\": \"^1.0.0\",\n- \"node-home-assistant\": \"^0.2.0\",\n+ \"node-home-assistant\": \"AYapejian/node-home-assistant#dev-master\",\n\"selectn\": \"^1.1.2\",\n\"serialize-javascript\": \"^1.4.0\"\n},\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | pull dev-master node-home-assistant while testing |
748,240 | 10.02.2018 11:47:53 | 18,000 | af90292274cb00adf236c481e561e0a61638012a | more service node fixes | [
{
"change_type": "MODIFY",
"old_path": "nodes/api_call-service/api_call-service.html",
"new_path": "nodes/api_call-service/api_call-service.html",
"diff": "service_domain: { value: '' },\nservice: { value: '' },\ndata: { value: '', validate: function(v) {\n+ // data isn't required since it could be either not needed or provided via payload\n+ if (!v) { return true; }\ntry { JSON.parse(v); return true; }\ncatch (e) { return false; }\n} }\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/api_call-service/api_call-service.js",
"new_path": "nodes/api_call-service/api_call-service.js",
"diff": "+/* eslint-disable camelcase */\nconst BaseNode = require('../../lib/base-node');\nmodule.exports = function(RED) {\n@@ -17,45 +18,51 @@ module.exports = function(RED) {\nsuper(nodeDefinition, RED, nodeOptions);\n}\nisObjectLike (v) {\n- return (v != null) && (typeof v == 'object'); // eslint-disable-line\n+ return (v !== null) && (typeof v === 'object');\n}\n// Disable connection status for api node\nsetConnectionStatus() {}\n-\n- onInput({ message }) {\n- let { service_domain, service, data } = this.nodeConfig;\n- if (data && !this.isObjectLike(data)) {\n+ tryToObject(v) {\n+ if (!v) return null;\ntry {\n- data = JSON.parse(data);\n- } catch (e) {}\n+ return JSON.parse(v);\n+ } catch (e) {\n+ return v;\n+ }\n}\n+ onInput({ message }) {\n+ let payloadDomain, payloadService, payloadData;\n- const pDomain = this.utils.reach('payload.domain', message);\n- const pService = this.utils.reach('payload.service', message);\n- const pData = this.utils.reach('payload.data', message);\n+ if (message && message.payload) {\n+ const payload = this.tryToObject(message.payload);\n+ payloadDomain = this.utils.reach('domain', payload);\n+ payloadService = this.utils.reach('service', payload);\n+ payloadData = this.utils.reach('data', payload);\n+ }\n+ const configDomain = this.nodeConfig.service_domain;\n+ const configService = this.nodeConfig.service;\n+ let configData = this.nodeConfig.data;\n+ configData = this.tryToObject(configData);\n- // domain and service are strings, if they exist in payload overwrite any config value\n- const apiDomain = pDomain || service_domain;\n- const apiService = pService || service;\n+ const apiDomain = payloadDomain || configDomain;\n+ const apiService = payloadService || configService;\nif (!apiDomain) throw new Error('call service node is missing api \"domain\" property, not found in config or payload');\nif (!apiService) throw new Error('call service node is missing api \"service\" property, not found in config or payload');\n- let apiData;\n// api data should be an object or falsey, if an object then attempt to merge with config value if also an object\n- if (this.isObjectLike(pData)) {\n- if (this.isObjectLike(data)) {\n- apiData = this.utils.merge({}, data, pData);\n- } else {\n- apiData = pData;\n- }\n- // Not an object, but maybe \"something\"\n- } else if (pData) {\n- apiData = pData;\n- } else {\n- apiData = null;\n+ let apiData;\n+\n+ const payloadDataIsObject = this.isObjectLike(payloadData);\n+ const configDataIsObject = this.isObjectLike(configData);\n+\n+ if (payloadDataIsObject && configDataIsObject) {\n+ apiData = JSON.stringify(this.utils.merge({}, configData, payloadData));\n+ } else if (payloadDataIsObject) {\n+ apiData = JSON.stringify(payloadData);\n+ } else if (configDataIsObject) {\n+ apiData = JSON.stringify(configData);\n}\n- apiData = (apiData && this.isObjectLike(apiData)) ? JSON.stringify(apiData) : null;\nthis.debugToClient(`Calling Service: ${apiDomain}:${apiService} -- ${apiData}`);\nreturn this.nodeConfig.server.api.callService(apiDomain, apiService, apiData)\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | more service node fixes |
748,240 | 10.02.2018 15:49:26 | 18,000 | 05b894430a69ec2ff68dc28226d5005a67e22166 | api-call-service node: ability to merge context into 'data' property, added output for node with data used to call service, added documentation | [
{
"change_type": "MODIFY",
"old_path": "nodes/api_call-service/api_call-service.html",
"new_path": "nodes/api_call-service/api_call-service.html",
"diff": "category: 'home_assistant',\ncolor: '#52C0F2',\ninputs: 1,\n- outputs: 0,\n+ outputs: 1,\nicon: 'router-wireless.png',\nalign: 'right',\npaletteLabel: 'call service',\nif (!v) { return true; }\ntry { JSON.parse(v); return true; }\ncatch (e) { return false; }\n- } }\n+ } },\n+ mergecontext: { value: null }\n},\noneditprepare: function () {\nconst NODE = this;\n<label for=\"node-input-name\"><i class=\"fa fa-tag\"></i> Name</label>\n<input type=\"text\" id=\"node-input-name\" placeholder=\"Name\">\n</div>\n- <!--<div class=\"form-tips\"><b>Tip:</b> This is here to help.</div>-->\n+\n<div class=\"form-row\">\n<label for=\"node-input-server\"><i class=\"fa fa-dot-circle-o\"></i> Server</label>\n<div class=\"form-row\">\n<label for=\"service_domain\"><i class=\"fa fa-cube\"></i> Domain</label>\n<input type=\"text\" id=\"service_domain\">\n-\n- <!--<label for=\"node-input-servicedomain\"><i class=\"fa fa-dot-circle-o\"></i> Domain</label>\n- <input type=\"text\" id=\"node-input-servicedomain\" placeholder=\"light\"/>-->\n</div>\n<div class=\"form-row\">\n<label for=\"service\"><i class=\"fa fa-cube\"></i> Service</label>\n<input type=\"text\" id=\"service\">\n-\n- <!--<label for=\"node-input-service\"><i class=\"fa fa-dot-circle-o\"></i> Service</label>\n- <input type=\"text\" id=\"node-input-service\" placeholder=\"toggle\"/>-->\n</div>\n<div class=\"form-row\">\n<input type=\"text\" id=\"node-input-data\" placeholder=\"{ entity_id: light.livingroom }\"/>\n</div>\n+ <div class=\"form-row\">\n+ <label for=\"node-input-mergecontext\"><i class=\"fa fa-dot-circle-o\"></i> Merge Context</label>\n+ <input type=\"text\" id=\"node-input-mergecontext\" placeholder=\"lightOptions\"/>\n+ </div>\n+\n<div id=\"service-data-desc\" class=\"form-row\">\n<h4>\nService: <span class=\"title\"></span>\n<script type=\"text/x-red\" data-help-name=\"api-call-service\">\n<p>Call a Home Assistant service</p>\n- <p>Set the node's domain, service and data defaults or allow the incoming message to define them, or both.</p>\n- <p>If the incoming message has a `payload` property with `domain`, `service` set it will override any defaults(if any) set. If data is provided\n- and is an obect or parseable into an object then it's data will be -merged- with the config data if set. </p>\n- <p>All other `msg.payload` properties are ignored</p>\n- <p> NOTE: Service and Domain have to be set, either by node config or incoming message for a service call to be made</p>\n+ <h3>Inputs</h3>\n+ <dl class=\"message-properties\">\n+ <dt class=\"optional\">\n+ payload.domain <span class=\"property-type\">string</span>\n+ </dt>\n+ <dd>Service domain to call</dd>\n+ <dt class=\"optional\">\n+ payload.service <span class=\"property-type\">string</span>\n+ </dt>\n+ <dd>Service service to call</dd>\n+ <dt class=\"optional\">\n+ payload.data <span class=\"property-type\">object</span>\n+ </dt>\n+ <dd>Service data to send with api call</dd>\n+ </dl>\n+\n+ <h3>Outputs</h3>\n+ <dl class=\"message-properties\">\n+ <dt>\n+ payload.domain <span class=\"property-type\">string</span>\n+ </dt>\n+ <dd>Service <code>domain</code> service was called with</dd>\n+ <dt>\n+ payload.service <span class=\"property-type\">string</span>\n+ </dt>\n+ <dd>Service <code>service</code> was called with</dd>\n+ <dt class=\"optional\">\n+ payload.data <span class=\"property-type\">object</span>\n+ </dt>\n+ <dd>Service <code>data</code> used in call, if one was used</dd>\n+ </dl>\n+\n+ <h3>Details</h3>\n+ <p>If the incoming message has a <code>payload</code> property with <code>domain</code>, <code>service</code> set it will override any config values if set.</p>\n+ <p>If the incoming message has a <code>payload.data</code> that is an object or parseable into an object these properties will be <strong>merged</strong> with any config values set.<p>\n+ <p>If the node has a property value in it's config for <code>Merge Context</code> then the <code>flow</code> and <code>global</code> contexts will be checked for this property which should be an object that will also be merged into the data payload.<p>\n+\n+ <h3>Merge Resolution</h3>\n+ <p>As seen above the <code>data</code> property has a lot going on in the way of data merging, in the end all of these are optional and the right most will win in the event that a property exists in multiple objects<p>\n+ <p>Config Data, Global Data, Flow Data, Payload Data ( payload data property always wins if provided )<p>\n+\n+ <h3>References</h3>\n+ <ul>\n+ <li><a href=\"https://home-assistant.io/developers/rest_api/#get-apiservices\">HA API call service</a></li>\n+ </ul>\n</script>\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/api_call-service/api_call-service.js",
"new_path": "nodes/api_call-service/api_call-service.js",
"diff": "@@ -8,6 +8,7 @@ module.exports = function(RED) {\nservice_domain: {},\nservice: {},\ndata: {},\n+ mergecontext: {},\nname: {},\nserver: { isNode: true }\n}\n@@ -31,39 +32,31 @@ module.exports = function(RED) {\n}\n}\nonInput({ message }) {\n- let payloadDomain, payloadService, payloadData;\n+ let payload, payloadDomain, payloadService;\nif (message && message.payload) {\n- const payload = this.tryToObject(message.payload);\n+ payload = this.tryToObject(message.payload);\npayloadDomain = this.utils.reach('domain', payload);\npayloadService = this.utils.reach('service', payload);\n- payloadData = this.utils.reach('data', payload);\n}\nconst configDomain = this.nodeConfig.service_domain;\nconst configService = this.nodeConfig.service;\n- let configData = this.nodeConfig.data;\n- configData = this.tryToObject(configData);\nconst apiDomain = payloadDomain || configDomain;\nconst apiService = payloadService || configService;\n+ const apiData = this.getApiData(payload);\nif (!apiDomain) throw new Error('call service node is missing api \"domain\" property, not found in config or payload');\nif (!apiService) throw new Error('call service node is missing api \"service\" property, not found in config or payload');\n- // api data should be an object or falsey, if an object then attempt to merge with config value if also an object\n- let apiData;\n-\n- const payloadDataIsObject = this.isObjectLike(payloadData);\n- const configDataIsObject = this.isObjectLike(configData);\n+ this.debug(`Calling Service: ${apiDomain}:${apiService} -- ${JSON.stringify(apiData || {})}`);\n- if (payloadDataIsObject && configDataIsObject) {\n- apiData = JSON.stringify(this.utils.merge({}, configData, payloadData));\n- } else if (payloadDataIsObject) {\n- apiData = JSON.stringify(payloadData);\n- } else if (configDataIsObject) {\n- apiData = JSON.stringify(configData);\n+ this.send({\n+ payload: {\n+ domain: apiDomain,\n+ service: apiService,\n+ data: apiData || null\n}\n-\n- this.debugToClient(`Calling Service: ${apiDomain}:${apiService} -- ${apiData}`);\n+ });\nreturn this.nodeConfig.server.api.callService(apiDomain, apiService, apiData)\n.catch(err => {\n@@ -71,6 +64,30 @@ module.exports = function(RED) {\nthis.error('Error calling service, home assistant api error', message);\n});\n}\n+\n+ getApiData(payload) {\n+ let apiData;\n+ let contextData = {};\n+\n+ let payloadData = this.utils.reach('data', payload);\n+ let configData = this.tryToObject(this.nodeConfig.data);\n+ payloadData = payloadData || {};\n+ configData = configData || {};\n+\n+ // Cacluate payload to send end priority ends up being 'Config, Global Ctx, Flow Ctx, Payload' with right most winning\n+ if (this.nodeConfig.mergecontext) {\n+ const ctx = this.node.context();\n+ let flowVal = ctx.flow.get(this.nodeConfig.mergecontext);\n+ let globalVal = ctx.global.get(this.nodeConfig.mergecontext);\n+ flowVal = flowVal || {};\n+ globalVal = globalVal || {};\n+ contextData = this.utils.merge({}, globalVal, flowVal);\n+ }\n+\n+ apiData = this.utils.merge({}, configData, contextData, payloadData);\n+ this.warn(apiData);\n+ return apiData;\n+ }\n}\nRED.nodes.registerType('api-call-service', CallServiceNode);\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | api-call-service node: ability to merge context into 'data' property, added output for node with data used to call service, added documentation |
748,240 | 10.02.2018 22:12:23 | 18,000 | 904e4446fa63c60d5cc33056d9983c2ccd6799a0 | server node: the server config node now publishes state, services and events on the global context, available to function nodes | [
{
"change_type": "MODIFY",
"old_path": "lib/base-node.js",
"new_path": "lib/base-node.js",
"diff": "@@ -11,7 +11,13 @@ const utils = {\nmerge,\nJoi,\nreach: (path, obj) => selectn(path, obj),\n- formatDate: (date) => dateFns.format(date, 'ddd, h:mm:ss A')\n+ formatDate: (date) => dateFns.format(date, 'ddd, h:mm:ss A'),\n+ toCamelCase(str) {\n+ return str.replace(/(?:^\\w|[A-Z]|\\b\\w|\\s+)/g, function(match, index) {\n+ if (+match === 0) return '';\n+ return index == 0 ? match.toLowerCase() : match.toUpperCase(); // eslint-disable-line\n+ });\n+ }\n};\nconst DEFAULT_OPTIONS = {\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/config-server/config-server.html",
"new_path": "nodes/config-server/config-server.html",
"diff": "</script>\n<script type=\"text/x-red\" data-template-name=\"server\">\n+\n<div class=\"form-row\">\n<label for=\"node-config-input-name\"><i class=\"fa fa-tag\"></i> Name</label>\n<input type=\"text\" id=\"node-config-input-name\" />\n<script type=\"text/x-red\" data-help-name=\"server\">\n<p>Home Assistant connection configuration</p>\n+\n+\n+ <h3>Config</h3>\n+ <dl class=\"message-properties\">\n+ <dt>\n+ Name <span class=\"property-type\">string</span>\n+ </dt>\n+ <dd>Label for this configuration, see details below for implications</dd>\n+ <dt>\n+ Base URL <span class=\"property-type\">string</span>\n+ </dt>\n+ <dd>The base url and port the home assistant instance can be reached at, for example: <code>http://192.168.0.100:8123</code> or <code>https://homeassistant.mysite.com</code></dd>\n+ <dt class=\"optional\">\n+ API Pass <span class=\"property-type\">string</span>\n+ </dt>\n+ <dd>Password used to contact the API, if one is needed</dd>\n+ </dl>\n+\n+ <h3>Details</h3>\n+ <p>Every node requires a configuration attached to define how to contact home assistant, that is this config node's main purpose.</p>\n+\n+ <h4>Context</h4>\n+ <p>Each config node will also make some data available on the global context, the <code>Name</code> value in this node is used as a, camelcased, namespace for those values</p>\n+ <p>Currently <code>states</code>, <code>services</code> and <code>events</code> is made available on the global context. <code>states</code> is always set to all available states at startup and updated whenever state changes occur so it should be always up to date. <code>services</code> and <code>events</code> is only updated on initial deploy.</p>\n+\n+ <h4>Context Example</h4>\n+ <p>Say we have a config node with name <code>My Awesome server</code>, with an entity setup in homeassistant as <code>switch.my_switch</code>. This state would be available within function nodes and you could fetch using something like the below code</p>\n+ <p>NOTE: It's likely one of the state or trigger nodes will better serve most use cases, this is simply provided as an option for more advanced cases, or to implement functionality I haven't thought of/gotten around to</p>\n+<pre>\n+const haCtx = global.get('homeassistant');\n+const configCtx = haCtx.myAwesomeServer;\n+const entityState = configCtx.states['switch.my_switch'];\n+return (entityState.state === 'on') ? true : false;\n+</pre>\n+\n+ <h3>Connection Issues</h3>\n+ <p>Communication with homeassistant is accomplished via a combination of ServerEvents and the REST API, if you are having troubles communicating with home assistant make sure you can access the API outside of node-red, but from the same server node-red is running on, using a REST client, curl, or any number of other methods to validate the connection<p>\n+\n+ <h3>References</h3>\n+ <ul>\n+ <li><a href=\"https://home-assistant.io/developers/rest_api\">HA REST API</a></li>\n+ </ul>\n</script>\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/config-server/config-server.js",
"new_path": "nodes/config-server/config-server.js",
"diff": "@@ -47,6 +47,11 @@ module.exports = function(RED) {\nconst HTTP_STATIC_OPTS = { root: require('path').join(__dirname, '..', '/_static'), dotfiles: 'deny' };\nthis.RED.httpAdmin.get('/homeassistant/static/*', function(req, res) { res.sendFile(req.params[0], HTTP_STATIC_OPTS) });\n+ this.setOnContext('states', []);\n+ this.setOnContext('services', []);\n+ this.setOnContext('events', []);\n+ this.setOnContext('isConnected', false);\n+\nif (this.nodeConfig.url && !this.homeAssistant) {\nthis.homeAssistant = new HomeAssistant({ baseUrl: this.nodeConfig.url, apiPass: this.nodeConfig.pass }, { startListening: false });\nthis.api = this.homeAssistant.api;\n@@ -55,12 +60,17 @@ module.exports = function(RED) {\nthis.events.addListener('ha_events:close', this.onHaEventsClose.bind(this));\nthis.events.addListener('ha_events:open', this.onHaEventsOpen.bind(this));\nthis.events.addListener('ha_events:error', this.onHaEventsError.bind(this));\n+ this.events.addListener('ha_events:state_changed', this.onHaStateChanged.bind(this));\nthis.homeAssistant.startListening()\n.catch(() => this.startListening());\n}\n}\n+ get nameAsCamelcase() {\n+ return this.utils.toCamelCase(this.nodeConfig.name);\n+ }\n+\n// This simply tries to connected every 2 seconds, after the initial connection is successful\n// reconnection attempts are handled by node-home-assistant. This could use some love obviously\nstartListening() {\n@@ -80,20 +90,53 @@ module.exports = function(RED) {\n}, 2000);\n}\n- onHaEventsOpen() {\n- // This is another hack that should be set in node-home-assistant\n- // when the connection is first made the states cache needs to be refreshed\n- this.homeAssistant.getStates(null, true);\n- this.homeAssistant.getServices(true);\n- this.homeAssistant.getEvents(true);\n+ setOnContext(key, value) {\n+ let haCtx = this.context().global.get('homeassistant');\n+ haCtx = haCtx || {};\n+ haCtx[this.nameAsCamelcase] = haCtx[this.nameAsCamelcase] || {};\n+ haCtx[this.nameAsCamelcase][key] = value;\n+ this.context().global.set('homeassistant', haCtx);\n+ }\n+\n+ getFromContext(key) {\n+ let haCtx = this.context().global.get('homeassistant');\n+ return (haCtx[this.nameAsCamelcase]) ? haCtx[this.nameAsCamelcase][key] : null;\n+ }\n+\n+ async onHaEventsOpen() {\n+ try {\n+ let states = await this.homeAssistant.getStates(null, true);\n+ this.setOnContext('states', states);\n+\n+ let services = await this.homeAssistant.getServices(true);\n+ this.setOnContext('services', services);\n+\n+ let events = await this.homeAssistant.getEvents(true);\n+ this.setOnContext('events', events);\n+\n+ this.setOnContext('isConnected', true);\n+\nthis.debug('config server event listener connected');\n+ } catch (e) {\n+ this.error(e);\n+ }\n+ }\n+\n+ onHaStateChanged(changedEntity) {\n+ const states = this.getFromContext('states');\n+ if (states) {\n+ states[changedEntity.entity_id] = changedEntity.event.new_state;\n+ this.setOnContext('states', states);\n+ }\n}\nonHaEventsClose() {\n+ this.setOnContext('isConnected', false);\nthis.debug('config server event listener closed');\n}\nonHaEventsError(err) {\n+ this.setOnContext('isConnected', false);\nthis.debug(err);\n}\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | server node: the server config node now publishes state, services and events on the global context, available to function nodes |
748,240 | 10.02.2018 22:32:41 | 18,000 | 153175f93beebf3e2bc75759dbc5180fcbfa289f | removed warn logging not needed | [
{
"change_type": "MODIFY",
"old_path": "nodes/api_call-service/api_call-service.js",
"new_path": "nodes/api_call-service/api_call-service.js",
"diff": "@@ -85,7 +85,6 @@ module.exports = function(RED) {\n}\napiData = this.utils.merge({}, configData, contextData, payloadData);\n- this.warn(apiData);\nreturn apiData;\n}\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | removed warn logging not needed |
748,240 | 11.02.2018 00:31:48 | 18,000 | 9e715a15f9a1c9309420167696b2ec67e43adfc5 | new node: time since state changed | [
{
"change_type": "MODIFY",
"old_path": ".gitignore",
"new_path": ".gitignore",
"diff": "@@ -6,3 +6,4 @@ settings.js\n_scratchpad_flows\n.DS_Store\n_docker-volumes/\n+./package-lock.json\n"
},
{
"change_type": "ADD",
"old_path": "nodes/time-since-state/icons/timer.png",
"new_path": "nodes/time-since-state/icons/timer.png",
"diff": "Binary files /dev/null and b/nodes/time-since-state/icons/timer.png differ\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "nodes/time-since-state/time-since-state.html",
"diff": "+<script type=\"text/javascript\">\n+ RED.nodes.registerType('time-since-state', {\n+ category: 'home_assistant',\n+ color: '#52C0F2',\n+ inputs: 1,\n+ outputs: 1,\n+ icon: \"timer.png\",\n+ paletteLabel: 'time since',\n+ label: function() { return this.name || `time since changed: ${this.entity_id}`; },\n+ defaults: {\n+ name: { value: '' },\n+ server: { value: '', type: 'server', required: true },\n+ updateinterval: { value: '', validate: (v) => !isNaN(v) },\n+ outputinitially: { value: false },\n+ outputonchanged: { value: false },\n+ entity_id: {\n+ value: '',\n+ required: true\n+ }\n+ },\n+ oneditprepare: function () {\n+ const $entityIdField = $('#entity_id');\n+ $entityIdField.val(this.entity_id);\n+\n+ const NODE = this;\n+ const $server = $('#node-input-server');\n+ const utils = {\n+ setDefaultServerSelection: function () {\n+ let defaultServer;\n+ RED.nodes.eachConfig(n => {\n+ if (n.type === 'server' && !defaultServer) defaultServer = n.id;\n+ });\n+ if (defaultServer) $server.val(defaultServer);\n+ }\n+ };\n+\n+ if (!NODE.server) {\n+ utils.setDefaultServerSelection();\n+ }\n+\n+ // Check that proper config is set\n+ const config = RED.nodes.node($('#node-input-server').val());\n+ const isConfigValid = (config && config.valid);\n+ // TODO: Doesn't seem to be working\n+ if (!isConfigValid) { $entityIdField.addClass('disabled'); }\n+ else { $entityIdField.removeClass('disabled'); }\n+\n+ $.get('/homeassistant/entities')\n+ .done((entities) => {\n+ this.availableEntities = JSON.parse(entities);\n+\n+ $entityIdField.autocomplete({\n+ source: this.availableEntities,\n+ minLength: 0,\n+ change: (evt,ui) => {\n+ const validSelection = (this.availableEntities.indexOf($(evt.target).val()) > -1);\n+ if (validSelection) { $(evt.target).removeClass('input-error'); }\n+ else { $(evt.target).addClass('input-error'); }\n+ }\n+ });\n+\n+ const validSelection = (this.availableEntities.indexOf(this.entity_id) > -1);\n+ if (validSelection) { $entityIdField.removeClass('input-error'); }\n+ else { $entityIdField.addClass('input-error'); }\n+ })\n+ .fail((err) => RED.notify(err.responseText, 'error'));\n+ },\n+ oneditsave: function() { this.entity_id = $(\"#entity_id\").val(); }\n+ });\n+</script>\n+\n+<script type=\"text/x-red\" data-template-name=\"time-since-state\">\n+ <div class=\"form-row\">\n+ <label for=\"node-input-name\"><i class=\"fa fa-tag\"></i> Name</label>\n+ <input type=\"text\" id=\"node-input-name\" placeholder=\"Name\">\n+ </div>\n+\n+ <div class=\"form-row\">\n+ <label for=\"node-input-server\"><i class=\"fa fa-server\"></i> Server</label>\n+ <input type=\"text\" id=\"node-input-server\" />\n+ </div>\n+\n+ <div class=\"form-row\">\n+ <label for=\"entity_id\"><i class=\"fa fa-cube\"></i> Entity ID</label>\n+ <input type=\"text\" id=\"entity_id\">\n+ </div>\n+\n+ <div class=\"form-row\">\n+ <label for=\"node-input-updateinterval\"><i class=\"fa fa-hand-paper-o\"></i> Update Interval</label>\n+ <input type=\"text\" id=\"node-input-updateinterval\" placeholder=\"10\"/>\n+ </div>\n+\n+ <div class=\"form-row\">\n+ <label for=\"node-input-outputonchanged\"><i class=\"fa fa-server\"></i> Output on Changed</label>\n+ <input type=\"checkbox\" id=\"node-input-outputonchanged\" />\n+ </div>\n+\n+ <div class=\"form-row\">\n+ <label for=\"node-input-outputinitially\"><i class=\"fa fa-server\"></i> Output Initially</label>\n+ <input type=\"checkbox\" id=\"node-input-outputinitially\" />\n+ </div>\n+</script>\n+\n+<script type=\"text/x-red\" data-help-name=\"time-since-state\">\n+ <p>Polls for state of given entity and outputs time since last changed</p>\n+\n+ <h3>Config</h3>\n+ <dl class=\"message-properties\">\n+ <dt>Update Interval<span class=\"property-type\">number</span></dt>\n+ <dd>Number of seconds between checking / sending updates</dd>\n+ <dt>Output Initially<span class=\"property-type\">boolean</span></dt>\n+ <dd>Output once on startup/deploy then on each interval</dd>\n+ </dl>\n+\n+ <h3>Outputs</h3>\n+ <dl class=\"message-properties\">\n+ <dt>topic (same as data.entity_id)<span class=\"property-type\">string</span></dt>\n+ <dd>Latest current state object received from home assistant</dd>\n+\n+ <dt>payload<span class=\"property-type\">string</span></dt>\n+ <dd>Time since changed</dd>\n+\n+ <dt>data <span class=\"property-type\">object</span></dt>\n+ <dd>The last known state for the entity</dd>\n+ </dl>\n+\n+ <h3>Details</h3>\n+ <p>Useful for either alerts for non-communicating devices (time since change > 1 day for example) or dashboard usage</p>\n+\n+ <h3>References</h3>\n+ <ul>\n+ <li><a href=\"https://home-assistant.io/docs/configuration/state_object/\">HA State Objects</a></li>\n+ </ul>\n+</script>\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "nodes/time-since-state/time-since-state.js",
"diff": "+/* eslint-disable camelcase */\n+const ta = require('time-ago');\n+const EventsNode = require('../../lib/events-node');\n+\n+module.exports = function(RED) {\n+ const nodeOptions = {\n+ config: {\n+ entity_id: {},\n+ updateinterval: {},\n+ outputinitially: {},\n+ outputonchanged: {}\n+ }\n+ };\n+\n+ class TimeSinceStateNode extends EventsNode {\n+ constructor(nodeDefinition) {\n+ super(nodeDefinition, RED, nodeOptions);\n+ this.init();\n+ }\n+\n+ init() {\n+ if (!this.nodeConfig.entity_id) throw new Error('Entity ID is required');\n+\n+ if (!this.timer) {\n+ const interval = (!this.nodeConfig.updateinterval || parseInt(this.nodeConfig.updateinterval) < 1) ? 1 : parseInt(this.nodeConfig.updateinterval);\n+ this.timer = setInterval(this.onTimer.bind(this), interval * 1000);\n+ }\n+\n+ if (this.nodeConfig.outputonchanged) {\n+ this.addEventClientListener({ event: `ha_events:state_changed:${this.nodeConfig.entity_id}`, handler: this.onTimer.bind(this) });\n+ }\n+\n+ if (this.nodeConfig.outputinitially) {\n+ process.nextTick(() => {\n+ this.onTimer();\n+ });\n+ }\n+ }\n+\n+ onClose(removed) {\n+ super.onClose();\n+ if (removed) {\n+ clearInterval(this.timer);\n+ }\n+ }\n+\n+ async onTimer() {\n+ try {\n+ const state = await this.getState(this.nodeConfig.entity_id);\n+ if (!state) {\n+ this.warn(`could not find state with entity_id \"${this.nodeConfig.entity_id}\"`);\n+ return;\n+ }\n+\n+ const dateChanged = this.calculateTimeSinceChanged(state);\n+ if (dateChanged) {\n+ const timeSinceChanged = ta.ago(dateChanged);\n+ const timeSinceChangedMs = Date.now() - dateChanged.getTime();\n+ this.send({\n+ topic: this.nodeConfig.entity_id,\n+ payload: { timeSinceChanged, timeSinceChangedMs, dateChanged, state }\n+ });\n+ } else {\n+ this.warn(`could not calculate time since changed for entity_id \"${this.nodeConfig.entity_id}\"`);\n+ }\n+ } catch (e) { throw e }\n+ }\n+\n+ calculateTimeSinceChanged(entityState) {\n+ const entityLastChanged = entityState.last_changed;\n+ return new Date(entityLastChanged);\n+ }\n+ // Try to fetch from cache, if not found then try and pull fresh\n+ async getState(entityId) {\n+ let state = await this.nodeConfig.server.homeAssistant.getStates(this.nodeConfig.entity_id);\n+ if (!state) {\n+ state = await this.nodeConfig.server.homeAssistant.getStates(this.nodeConfig.entity_id, true);\n+ }\n+ return state;\n+ }\n+ }\n+ RED.nodes.registerType('time-since-state', TimeSinceStateNode);\n+};\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"api-call-service\": \"nodes/api_call-service/api_call-service.js\",\n\"api-current-state\": \"nodes/api_current-state/api_current-state.js\",\n\"api-get-history\": \"nodes/api_get-history/api_get-history.js\",\n- \"api-render-template\": \"nodes/api_render-template/api_render-template.js\"\n+ \"api-render-template\": \"nodes/api_render-template/api_render-template.js\",\n+ \"time-since-state\": \"nodes/time-since-state/time-since-state.js\"\n}\n},\n\"dependencies\": {\n\"joi\": \"^13.1.1\",\n\"lodash.merge\": \"^4.6.0\",\n\"lowdb\": \"^1.0.0\",\n- \"node-red\": \"node-red/node-red#0.18.2\",\n\"node-home-assistant\": \"AYapejian/node-home-assistant#dev-master\",\n+ \"node-red\": \"node-red/node-red#0.18.2\",\n\"selectn\": \"^1.1.2\",\n- \"serialize-javascript\": \"^1.4.0\"\n+ \"serialize-javascript\": \"^1.4.0\",\n+ \"time-ago\": \"^0.2.1\"\n},\n\"devDependencies\": {\n\"eslint\": \"^4.8.0\",\n"
},
{
"change_type": "MODIFY",
"old_path": "yarn.lock",
"new_path": "yarn.lock",
"diff": "@@ -4519,6 +4519,10 @@ through@2, through@^2.3.6, through@~2.3, through@~2.3.1, through@~2.3.4, through\nversion \"2.3.8\"\nresolved \"https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5\"\n+time-ago@^0.2.1:\n+ version \"0.2.1\"\n+ resolved \"https://registry.yarnpkg.com/time-ago/-/time-ago-0.2.1.tgz#4abcb7fb8c8cbb1efd9575ab8b30ec699e8e05a9\"\n+\ntimeago.js@^3.0.2:\nversion \"3.0.2\"\nresolved \"https://registry.yarnpkg.com/timeago.js/-/timeago.js-3.0.2.tgz#32a67e7c0d887ea42ca588d3aae26f77de5e76cc\"\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | new node: time since state changed |
748,240 | 11.02.2018 02:02:15 | 18,000 | 24832964d33345ea65654a697d92f6f44243c0e5 | fix for timers not clearing correctly | [
{
"change_type": "MODIFY",
"old_path": "nodes/time-since-state/time-since-state.js",
"new_path": "nodes/time-since-state/time-since-state.js",
"diff": "@@ -39,8 +39,9 @@ module.exports = function(RED) {\nonClose(removed) {\nsuper.onClose();\n- if (removed) {\n+ if (this.timer) {\nclearInterval(this.timer);\n+ this.timer = null;\n}\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | fix for timers not clearing correctly |
748,240 | 11.02.2018 21:45:57 | 18,000 | f471a999940a11acaf14ec165ac842ab3f1b0cd8 | last changed node renamed to poll state to cover more use cases | [
{
"change_type": "RENAME",
"old_path": "nodes/time-since-state/icons/timer.png",
"new_path": "nodes/poll-state/icons/timer.png",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "nodes/time-since-state/time-since-state.html",
"new_path": "nodes/poll-state/poll-state.html",
"diff": "<script type=\"text/javascript\">\n- RED.nodes.registerType('time-since-state', {\n+ RED.nodes.registerType('poll-state', {\ncategory: 'home_assistant',\ncolor: '#52C0F2',\ninputs: 1,\noutputs: 1,\nicon: \"timer.png\",\n- paletteLabel: 'time since',\n- label: function() { return this.name || `time since changed: ${this.entity_id}`; },\n+ paletteLabel: 'poll state',\n+ label: function() { return this.name || `poll state: ${this.entity_id}`; },\ndefaults: {\nname: { value: '' },\nserver: { value: '', type: 'server', required: true },\n});\n</script>\n-<script type=\"text/x-red\" data-template-name=\"time-since-state\">\n+<script type=\"text/x-red\" data-template-name=\"poll-state\">\n<div class=\"form-row\">\n<label for=\"node-input-name\"><i class=\"fa fa-tag\"></i> Name</label>\n<input type=\"text\" id=\"node-input-name\" placeholder=\"Name\">\n</div>\n</script>\n-<script type=\"text/x-red\" data-help-name=\"time-since-state\">\n+<script type=\"text/x-red\" data-help-name=\"poll-state\">\n<p>Polls for state of given entity and outputs time since last changed</p>\n<h3>Config</h3>\n<h3>Outputs</h3>\n<dl class=\"message-properties\">\n- <dt>topic (same as data.entity_id)<span class=\"property-type\">string</span></dt>\n- <dd>Latest current state object received from home assistant</dd>\n+ <dt>topic<span class=\"property-type\">string</span></dt>\n+ <dd>entity_id of changed entity</dd>\n- <dt>payload<span class=\"property-type\">string</span></dt>\n- <dd>Time since changed</dd>\n+ <dt>payload.timeSinceChanged<span class=\"property-type\">string</span></dt>\n+ <dd>Human readable format string of time since last updated, example \"1 hour ago\"</dd>\n- <dt>data <span class=\"property-type\">object</span></dt>\n- <dd>The last known state for the entity</dd>\n+ <dt>payload.timeSinceChangedMs<span class=\"property-type\">number</span></dt>\n+ <dd>Number of milliseconds since last changed</dd>\n+\n+ <dt>payload.dateChanged<span class=\"property-type\">string</span></dt>\n+ <dd>ISO date string of the date when the entity last changed</dd>\n+\n+ <dt>payload.data<span class=\"property-type\">object</span></dt>\n+ <dd>The last known state of the entity</dd>\n</dl>\n<h3>Details</h3>\n- <p>Useful for either alerts for non-communicating devices (time since change > 1 day for example) or dashboard usage</p>\n+ <p>Polls for state at regular intervals, optionally also outputing at start and when state changes. Useful for either alerts for non-communicating devices (time since change > 1 day for example) or dashboard graphs with consistent interval charts</p>\n+ <p>NOTE: The last changed calculation is based on homeassistant's <code>last_changed</code> property so anything that changes that field will result in your last changed time outputted here to be changed.</p>\n<h3>References</h3>\n<ul>\n"
},
{
"change_type": "RENAME",
"old_path": "nodes/time-since-state/time-since-state.js",
"new_path": "nodes/poll-state/poll-state.js",
"diff": "@@ -59,7 +59,7 @@ module.exports = function(RED) {\nconst timeSinceChangedMs = Date.now() - dateChanged.getTime();\nthis.send({\ntopic: this.nodeConfig.entity_id,\n- payload: { timeSinceChanged, timeSinceChangedMs, dateChanged, state }\n+ payload: { timeSinceChanged, timeSinceChangedMs, dateChanged, data: state }\n});\n} else {\nthis.warn(`could not calculate time since changed for entity_id \"${this.nodeConfig.entity_id}\"`);\n@@ -80,5 +80,5 @@ module.exports = function(RED) {\nreturn state;\n}\n}\n- RED.nodes.registerType('time-since-state', TimeSinceStateNode);\n+ RED.nodes.registerType('poll-state', TimeSinceStateNode);\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"api-current-state\": \"nodes/api_current-state/api_current-state.js\",\n\"api-get-history\": \"nodes/api_get-history/api_get-history.js\",\n\"api-render-template\": \"nodes/api_render-template/api_render-template.js\",\n- \"time-since-state\": \"nodes/time-since-state/time-since-state.js\"\n+ \"poll-state\": \"nodes/poll-state/poll-state.js\"\n}\n},\n\"dependencies\": {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | last changed node renamed to poll state to cover more use cases |
748,240 | 14.02.2018 22:42:14 | 18,000 | 9ebc4110221a9747edb4d037d85c4df3022f6105 | non event nodes: fix for displaying connection status even though not event nodes | [
{
"change_type": "MODIFY",
"old_path": ".vscode/launch.json",
"new_path": ".vscode/launch.json",
"diff": "\"address\": \"localhost\",\n\"port\": 9123,\n\"trace\": false,\n-\n\"skipFiles\": [\n\"<node_internals>/**/*.js\"\n]\n"
},
{
"change_type": "MODIFY",
"old_path": "_docker/home-assistant/root-fs/config/configuration.yaml",
"new_path": "_docker/home-assistant/root-fs/config/configuration.yaml",
"diff": "@@ -67,3 +67,14 @@ binary_sensor:\nstate_topic: !env_var MQTT_DEV_BINARY_SENSOR_TOPIC\npayload_on: '1'\npayload_off: '0'\n+\n+input_select:\n+ time_of_day:\n+ name: Time of Day\n+ options:\n+ - Morning\n+ - Afternoon\n+ - Evening\n+ - Party Time\n+ initial: Morning\n+ icon: mdi:schedule\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/base-node.js",
"new_path": "lib/base-node.js",
"diff": "@@ -63,7 +63,6 @@ class BaseNode {\nconst name = this.reach('nodeConfig.name');\nthis.debug(`instantiated node, name: ${name || 'undefined'}`);\n- this.updateConnectionStatus();\n}\nasync getDb() {\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/events-node.js",
"new_path": "lib/events-node.js",
"diff": "@@ -19,7 +19,7 @@ class EventsNode extends BaseNode {\nthis.addEventClientListener({ event: 'ha_events:open', handler: this.onHaEventsOpen.bind(this) });\nthis.addEventClientListener({ event: 'ha_events:error', handler: this.onHaEventsError.bind(this) });\n- // this.setConnectionStatus(this.isConnected);\n+ this.updateConnectionStatus();\n}\naddEventClientListener({ event, handler }) {\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/api_current-state/api_current-state.js",
"new_path": "nodes/api_current-state/api_current-state.js",
"diff": "@@ -27,6 +27,7 @@ module.exports = function(RED) {\nsuper(nodeDefinition, RED, nodeOptions);\n}\n+ /* eslint-disable camelcase */\nonInput({ parsedMessage, message }) {\nconst entity_id = parsedMessage.entity_id.value;\nconst logAndContinueEmpty = (logMsg) => { this.node.warn(logMsg); return ({ payload: {}}) };\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/poll-state/poll-state.html",
"new_path": "nodes/poll-state/poll-state.html",
"diff": "<script type=\"text/javascript\">\nRED.nodes.registerType('poll-state', {\ncategory: 'home_assistant',\n- color: '#52C0F2',\n+ color: '#038FC7',\ninputs: 1,\noutputs: 1,\n- icon: \"timer.png\",\n+ icon: 'timer.png',\npaletteLabel: 'poll state',\nlabel: function() { return this.name || `poll state: ${this.entity_id}`; },\ndefaults: {\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/server-events-state-changed/server-events-state-changed.html",
"new_path": "nodes/server-events-state-changed/server-events-state-changed.html",
"diff": "defaults: {\nname: { value: '' },\nserver: { value: '', type: 'server', required: true },\n- entityidfilter: { value: '' },\n- entityidfiltertype: { value: '' },\n+ entityidfilter: { value: '', required: true },\n+ entityidfiltertype: { value: 'substring' },\nhaltifstate: { value: '' }\n},\ninputs: 0,\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/server-events-state-changed/server-events-state-changed.js",
"new_path": "nodes/server-events-state-changed/server-events-state-changed.js",
"diff": "+/* eslint-disable camelcase */\nconst EventsNode = require('../../lib/events-node');\nmodule.exports = function(RED) {\nconst nodeOptions = {\n- debug: true,\nconfig: {\nentityidfilter: (nodeDef) => {\nif (!nodeDef.entityidfilter) return undefined;\n@@ -25,21 +25,11 @@ module.exports = function(RED) {\nonHaEventsStateChanged (evt) {\nconst { entity_id, event } = evt;\n- // TODO: Infrequent issue seen where event encountered without new_state, logging to pick up info\n- if (!event || !event.new_state) {\n- this.debug('Warning, event encountered without new_state');\n- this.debug(JSON.stringify(event));\n- this.warn(event);\n- return null;\n- }\n-\nconst shouldHaltIfState = this.shouldHaltIfState(event);\nconst shouldIncludeEvent = this.shouldIncludeEvent(entity_id);\nif (shouldHaltIfState) {\n- // TODO: Change all status to use a node option (log flow messages?) and log this on a\n- // per node basis rather than flashing status\n- this.warn('state halted status');\n+ this.debug('flow halted due to \"halt if state\" setting');\nreturn null;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"server-events\": \"nodes/server-events-all/server-events-all.js\",\n\"server-state-changed\": \"nodes/server-events-state-changed/server-events-state-changed.js\",\n\"trigger-state\": \"nodes/trigger-state/trigger-state.js\",\n+ \"poll-state\": \"nodes/poll-state/poll-state.js\",\n\"api-call-service\": \"nodes/api_call-service/api_call-service.js\",\n\"api-current-state\": \"nodes/api_current-state/api_current-state.js\",\n\"api-get-history\": \"nodes/api_get-history/api_get-history.js\",\n- \"api-render-template\": \"nodes/api_render-template/api_render-template.js\",\n- \"poll-state\": \"nodes/poll-state/poll-state.js\"\n+ \"api-render-template\": \"nodes/api_render-template/api_render-template.js\"\n}\n},\n\"dependencies\": {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | non event nodes: fix for displaying connection status even though not event nodes |
748,240 | 15.02.2018 00:15:53 | 18,000 | 58329edbe1b91ecedafca460a2478f4355d22fbc | poll state: should not have input, fix trigger output condition message was undefined | [
{
"change_type": "MODIFY",
"old_path": "nodes/poll-state/poll-state.html",
"new_path": "nodes/poll-state/poll-state.html",
"diff": "RED.nodes.registerType('poll-state', {\ncategory: 'home_assistant',\ncolor: '#038FC7',\n- inputs: 1,\n+ inputs: 0,\noutputs: 1,\nicon: 'timer.png',\npaletteLabel: 'poll state',\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/trigger-state/trigger-state.js",
"new_path": "nodes/trigger-state/trigger-state.js",
"diff": "+\n/* eslint-disable camelcase */\nconst EventsNode = require('../../lib/events-node');\n@@ -195,7 +196,7 @@ module.exports = function(RED) {\n}\nif (output.messageType === 'default') {\n- return eventMessage;\n+ return { topic: eventMessage.entity_id, payload: eventMessage.event.new_state.state, data: eventMessage };\n}\ntry {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | poll state: should not have input, fix trigger output condition message was undefined |
748,239 | 15.02.2018 10:19:46 | -7,200 | 98f1218b8b89bc22069ddc211d0e8ee68c865d4b | Note of server URL when running inside container
It isn't obvious what server node base url to use when running inside container. It's worth noting it also here. | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -15,6 +15,8 @@ $ npm install node-red-contrib-home-assistant\n# then restart node-red\n```\n+If you are running Node Red inside Hass.io addon/container you can use Hass.io API Proxy address `http://hassio/homeassistant` as Home Assistant server address (server node Base URL). This way you don't need any real network address.\n+\n---\n## Included Nodes\nThe installed nodes have more detailed information in the node-red info pane shown when the node is selected. Below is a quick summary\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Note of server URL when running inside container
It isn't obvious what server node base url to use when running inside container. It's worth noting it also here. |
748,240 | 15.02.2018 15:22:25 | 18,000 | b87a7b2af961ecf5a03b38886b2e924003801d97 | upped node-home-assistant version to 0.2.1 | [
{
"change_type": "MODIFY",
"old_path": "_docker/config.env",
"new_path": "_docker/config.env",
"diff": "@@ -13,17 +13,4 @@ HA_MQTT_CLIENT_ID=home-assistant-dev\nHA_HTTP_API_PASSWORD=password\nHA_LOGGER_DEFAULT=info\n-MQTT_HOST=mqtt\n-MQTT_PORT=1883\n-MQTT_LISTENER_TOPIC=dev/#\n-\n-MQTT_DEV_BINARY_SENSOR_INTERVAL=60\n-MQTT_DEV_BINARY_SENSOR_TOPIC=dev/mqtt-dev-binary-sensor/state\n-\n-MQTT_DEV_SENSOR_INTERVAL=30\n-MQTT_DEV_SENSOR_TOPIC=dev/mqtt-dev-sensor/state\n-\nNODE_RED_URL=http://localhost:1880\n-\n-\n-\n"
},
{
"change_type": "MODIFY",
"old_path": "_docker/docker-compose.mapped.yml",
"new_path": "_docker/docker-compose.mapped.yml",
"diff": "version: '3.1'\nservices:\n- mqtt:\n- container_name: mqtt\n- env_file: ./config.env\n- image: mqtt:local\n- build:\n- context: ./mqtt\n- ports:\n- - 1883:1883\n- - 9001:9001\n-\n- mqtt-listener:\n- image: mqtt:local\n- container_name: mqtt-listener\n- command: /listener-cmd.sh\n- env_file: ./config.env\n- depends_on:\n- - mqtt\n-\n- mqtt-dev-sensor:\n- image: mqtt:local\n- container_name: mqtt-dev-sensor\n- command: /dev-sensor.sh\n- env_file: ./config.env\n- depends_on:\n- - mqtt\n-\n- mqtt-dev-binary-sensor:\n- image: mqtt:local\n- container_name: mqtt-dev-binary-sensor\n- command: /dev-binary-sensor.sh\n- env_file: ./config.env\n- depends_on:\n- - mqtt\n-\nnode-red:\ncontainer_name: node-red\nenv_file: ./config.env\n"
},
{
"change_type": "MODIFY",
"old_path": "_docker/docker-compose.yml",
"new_path": "_docker/docker-compose.yml",
"diff": "version: '3.1'\nservices:\n- mqtt:\n- container_name: mqtt\n- env_file: ./config.env\n- image: mqtt:local\n- build:\n- context: ./mqtt\n- ports:\n- - 1883:1883\n- - 9001:9001\n-\n- mqtt-listener:\n- image: mqtt:local\n- container_name: mqtt-listener\n- command: /listener-cmd.sh\n- env_file: ./config.env\n- depends_on:\n- - mqtt\n-\n- mqtt-dev-sensor:\n- image: mqtt:local\n- container_name: mqtt-dev-sensor\n- command: /dev-sensor.sh\n- env_file: ./config.env\n- depends_on:\n- - mqtt\n-\n- mqtt-dev-binary-sensor:\n- image: mqtt:local\n- container_name: mqtt-dev-binary-sensor\n- command: /dev-binary-sensor.sh\n- env_file: ./config.env\n- depends_on:\n- - mqtt\n-\nnode-red:\n- container_name: node-red\nenv_file: ./config.env\n- build:\n- context: ./node-red\n+ build: ./node-red\ncommand: npm run dev:watch\nvolumes:\n- '..:/data/node_modules/node-red-contrib-home-assistant'\n- # - './node-red/root-fs/data-dev/flows.json:/data-dev/flows.json' # Map flows file for easy commitable examples building\n+ - './node-red/root-fs/data/flows.json:/data/flows.json' # Map flows file for easy commitable examples building\nports:\n- 1880:1880\n- 9123:9229\nhome-assistant:\n- container_name: home-assistant\nenv_file: ./config.env\n- build:\n- context: ./home-assistant\n+ build: ./home-assistant\n# While messing with HA config map the repo config to the container for easy changes\n- # volumes:\n- # - './home-assistant/root-fs/config/configuration.yaml:/config/configuration.yaml'\n+ volumes:\n+ - './home-assistant/root-fs/config/configuration.yaml:/config/configuration.yaml'\nports:\n- 8300:8300\n- 8123:8123\n- depends_on:\n- - mqtt\n"
},
{
"change_type": "MODIFY",
"old_path": "_docker/home-assistant/root-fs/config/configuration.yaml",
"new_path": "_docker/home-assistant/root-fs/config/configuration.yaml",
"diff": "@@ -10,11 +10,6 @@ homeassistant:\nhttp:\napi_password: !env_var HA_HTTP_API_PASSWORD\n-mqtt:\n- broker: !env_var MQTT_HOST\n- port: !env_var MQTT_PORT\n- client_id: !env_var HA_MQTT_CLIENT_ID\n-\nlogger:\ndefault: !env_var HA_LOGGER_DEFAULT\n@@ -49,25 +44,6 @@ panel_iframe:\n# service: switch.toggle\n# entity_id: light.kitchen_light\n-# Example configuration.yml entry\n-switch:\n- - platform: mqtt\n- name: MQTT Dev Switch\n- command_topic: dev/mqtt-dev-switch/cmd\n- state_topic: dev/mqtt-dev-switch/state\n-\n-sensor:\n- - platform: mqtt\n- name: MQTT Dev Sensor\n- state_topic: !env_var MQTT_DEV_SENSOR_TOPIC\n-\n-binary_sensor:\n- - platform: mqtt\n- name: MQTT Dev Binary Sensor\n- state_topic: !env_var MQTT_DEV_BINARY_SENSOR_TOPIC\n- payload_on: '1'\n- payload_off: '0'\n-\ninput_select:\ntime_of_day:\nname: Time of Day\n@@ -78,3 +54,27 @@ input_select:\n- Party Time\ninitial: Morning\nicon: mdi:schedule\n+\n+input_number:\n+ global_light_level:\n+ name: Global Light Level\n+ initial: 10\n+ min: 1\n+ max: 100\n+ step: 5\n+\n+input_boolean:\n+ notify_home:\n+ name: Use Global Light Level\n+ initial: off\n+ icon: mdi:lightbulb_outline\n+\n+input_datetime:\n+ only_date:\n+ name: Input with only date\n+ has_date: true\n+ has_time: false\n+ only_time:\n+ name: Input with only time\n+ has_date: false\n+ has_time: true\n"
},
{
"change_type": "MODIFY",
"old_path": "_docker/node-red/root-fs/app/package.json",
"new_path": "_docker/node-red/root-fs/app/package.json",
"diff": "\"dev:watch\": \"/app/node_modules/.bin/nodemon --config $NODEMON_CONFIG --exec 'sleep 0.5; node --inspect=0.0.0.0:9229 /app/node_modules/node-red/red.js -v --userDir $USER_DIR $FLOWS'\"\n},\n\"dependencies\": {\n- \"node-red\": \"0.17.5\",\n+ \"node-red\": \"0.18.2\",\n\"nodemon\": \"1.14.11\"\n},\n\"engines\": {\n"
},
{
"change_type": "MODIFY",
"old_path": "_docker/node-red/root-fs/data/flows.json",
"new_path": "_docker/node-red/root-fs/data/flows.json",
"diff": "[\n- {\n- \"id\": \"91829608.660cc8\",\n- \"type\": \"tab\",\n- \"label\": \"Simple Test\"\n- },\n- {\n- \"id\": \"ac309840.633668\",\n- \"type\": \"tab\",\n- \"label\": \"Current State\",\n- \"disabled\": false,\n- \"info\": \"\"\n- },\n- {\n- \"id\": \"75d3404c.f8ea8\",\n- \"type\": \"tab\",\n- \"label\": \"History\",\n- \"disabled\": false,\n- \"info\": \"\"\n- },\n- {\n- \"id\": \"a9b7da37.df64a8\",\n- \"type\": \"tab\",\n- \"label\": \"All Nodes\",\n- \"disabled\": false,\n- \"info\": \"\"\n- },\n- {\n- \"id\": \"aedb3267.4ec5f8\",\n- \"type\": \"server\",\n- \"z\": \"\",\n- \"name\": \"Home Assistant\",\n- \"url\": \"http://home-assistant:8123\",\n- \"pass\": \"password\"\n- },\n- {\n- \"id\": \"71f7b01d.b0b6b\",\n- \"type\": \"debug\",\n- \"z\": \"91829608.660cc8\",\n- \"name\": \"\",\n- \"active\": true,\n- \"console\": \"false\",\n- \"complete\": \"true\",\n- \"x\": 390,\n- \"y\": 40,\n- \"wires\": []\n- },\n- {\n- \"id\": \"d5ab9d80.758ce8\",\n- \"type\": \"server-state-changed\",\n- \"z\": \"91829608.660cc8\",\n- \"name\": \"\",\n- \"server\": \"aedb3267.4ec5f8\",\n- \"entityidfilter\": \"\",\n- \"haltifstate\": \"\",\n- \"x\": 150,\n- \"y\": 40,\n- \"wires\": [\n- [\n- \"71f7b01d.b0b6b\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"a450a11.4bb41e\",\n- \"type\": \"inject\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"Inject entity_id\",\n- \"topic\": \"\",\n- \"payload\": \"{\\\"entity_id\\\":\\\"binary_sensor.mqtt_dev_binary_sensor\\\"}\",\n- \"payloadType\": \"json\",\n- \"repeat\": \"\",\n- \"crontab\": \"\",\n- \"once\": false,\n- \"x\": 150,\n- \"y\": 220,\n- \"wires\": [\n- [\n- \"1ab59da9.008bf2\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"1b506d57.f6bdeb\",\n- \"type\": \"server-events\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"Events: All\",\n- \"server\": \"aedb3267.4ec5f8\",\n- \"x\": 100,\n- \"y\": 100,\n- \"wires\": [\n- [\n- \"cfe34d00.3f0af8\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"49e83647.76b448\",\n- \"type\": \"server-state-changed\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"Events: State Changed\",\n- \"server\": \"aedb3267.4ec5f8\",\n- \"entityidfilter\": \"binary_sensor.mqtt_dev_binary_sensor\",\n- \"haltifstate\": \"\",\n- \"x\": 140,\n- \"y\": 150,\n- \"wires\": [\n- [\n- \"3f8cfe6a.408b6a\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"949e61e9.cd005\",\n- \"type\": \"api-current-state\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"Current State\",\n- \"server\": \"aedb3267.4ec5f8\",\n- \"halt_if\": \"\",\n- \"entity_id\": \"binary_sensor.mqtt_dev_binary_sensor\",\n- \"x\": 360,\n- \"y\": 300,\n- \"wires\": [\n- [\n- \"2aa47700.30b86a\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"70716f8b.302608\",\n- \"type\": \"inject\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"Run\",\n- \"topic\": \"\",\n- \"payload\": \"\",\n- \"payloadType\": \"date\",\n- \"repeat\": \"\",\n- \"crontab\": \"\",\n- \"once\": false,\n- \"x\": 110,\n- \"y\": 300,\n- \"wires\": [\n- [\n- \"949e61e9.cd005\",\n- \"1236c799.f6e78\",\n- \"640855fc.4c2c9c\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"1236c799.f6e78\",\n- \"type\": \"api-render-template\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"Get Template\",\n- \"server\": \"aedb3267.4ec5f8\",\n- \"template\": \"{% for state in states.sensor %}\\n {{ state.entity_id }}={{ state.state }},\\n{% endfor %}\",\n- \"x\": 350,\n- \"y\": 420,\n- \"wires\": [\n- [\n- \"b5c0827d.077f28\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"2aa47700.30b86a\",\n- \"type\": \"debug\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"\",\n- \"active\": true,\n- \"console\": \"false\",\n- \"complete\": \"true\",\n- \"x\": 545,\n- \"y\": 300,\n- \"wires\": []\n- },\n- {\n- \"id\": \"64ea9766.90aa5\",\n- \"type\": \"debug\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"\",\n- \"active\": true,\n- \"console\": \"false\",\n- \"complete\": \"true\",\n- \"x\": 550,\n- \"y\": 360,\n- \"wires\": []\n- },\n- {\n- \"id\": \"b5c0827d.077f28\",\n- \"type\": \"debug\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"\",\n- \"active\": true,\n- \"console\": \"false\",\n- \"complete\": \"true\",\n- \"x\": 550,\n- \"y\": 420,\n- \"wires\": []\n- },\n- {\n- \"id\": \"3f8cfe6a.408b6a\",\n- \"type\": \"debug\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"\",\n- \"active\": true,\n- \"console\": \"false\",\n- \"complete\": \"true\",\n- \"x\": 340,\n- \"y\": 150,\n- \"wires\": []\n- },\n- {\n- \"id\": \"cfe34d00.3f0af8\",\n- \"type\": \"debug\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"\",\n- \"active\": false,\n- \"console\": \"false\",\n- \"complete\": \"true\",\n- \"x\": 340,\n- \"y\": 100,\n- \"wires\": []\n- },\n- {\n- \"id\": \"640855fc.4c2c9c\",\n- \"type\": \"api-get-history\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"\",\n- \"server\": \"aedb3267.4ec5f8\",\n- \"startdate\": \"\",\n- \"x\": 350,\n- \"y\": 360,\n- \"wires\": [\n- [\n- \"64ea9766.90aa5\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"1ab59da9.008bf2\",\n- \"type\": \"api-current-state\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"\",\n- \"server\": \"aedb3267.4ec5f8\",\n- \"halt_if\": \"\",\n- \"entity_id\": \"sensor.mqtt_dev_sensor\",\n- \"x\": 415,\n- \"y\": 220,\n- \"wires\": [\n- [\n- \"64fe8cc3.21d444\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"64fe8cc3.21d444\",\n- \"type\": \"debug\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"\",\n- \"active\": true,\n- \"console\": \"false\",\n- \"complete\": \"true\",\n- \"x\": 645,\n- \"y\": 220,\n- \"wires\": []\n- },\n- {\n- \"id\": \"44129cae.5bab0c\",\n- \"type\": \"api-current-state\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"\",\n- \"server\": \"aedb3267.4ec5f8\",\n- \"halt_if\": \"\",\n- \"entity_id\": \"sensor.mqtt_dev_sensor\",\n- \"x\": 370,\n- \"y\": 100,\n- \"wires\": [\n- [\n- \"e3a5a997.d75e4\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"d4f47b6c.ad4fa\",\n- \"type\": \"inject\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"\",\n- \"topic\": \"\",\n- \"payload\": \"\",\n- \"payloadType\": \"date\",\n- \"repeat\": \"\",\n- \"crontab\": \"\",\n- \"once\": false,\n- \"x\": 140,\n- \"y\": 100,\n- \"wires\": [\n- [\n- \"44129cae.5bab0c\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"e3a5a997.d75e4\",\n- \"type\": \"debug\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"\",\n- \"active\": true,\n- \"console\": \"false\",\n- \"complete\": \"true\",\n- \"x\": 650,\n- \"y\": 100,\n- \"wires\": []\n- },\n- {\n- \"id\": \"8a2c0f6b.ead54\",\n- \"type\": \"comment\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"Basic fetching of current state\",\n- \"info\": \"\",\n- \"x\": 150,\n- \"y\": 50,\n- \"wires\": []\n- },\n- {\n- \"id\": \"c6f358bf.ee154\",\n- \"type\": \"comment\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"Override the current state node's pre-configured entity_id value\",\n- \"info\": \"\",\n- \"x\": 260,\n- \"y\": 170,\n- \"wires\": []\n- },\n- {\n- \"id\": \"7c6eac6c.6fdba4\",\n- \"type\": \"inject\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"\",\n- \"topic\": \"\",\n- \"payload\": \"\",\n- \"payloadType\": \"date\",\n- \"repeat\": \"\",\n- \"crontab\": \"\",\n- \"once\": false,\n- \"x\": 140,\n- \"y\": 350,\n- \"wires\": [\n- [\n- \"b3481b2.bb19068\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"b3481b2.bb19068\",\n- \"type\": \"api-call-service\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"Set MQTT Binary sensor to off state\",\n- \"server\": \"aedb3267.4ec5f8\",\n- \"service_domain\": \"mqtt\",\n- \"service\": \"publish\",\n- \"data\": \"{\\\"topic\\\":\\\"dev/mqtt-dev-binary-sensor/state\\\",\\\"payload\\\":\\\"0\\\"}\",\n- \"x\": 540,\n- \"y\": 350,\n- \"wires\": []\n- },\n- {\n- \"id\": \"c3f15720.5a901\",\n- \"type\": \"api-current-state\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"Get MQTT Binary Sensor state, halt if off\",\n- \"server\": \"aedb3267.4ec5f8\",\n- \"halt_if\": \"off\",\n- \"entity_id\": \"binary_sensor.mqtt_dev_binary_sensor\",\n- \"x\": 420,\n- \"y\": 520,\n- \"wires\": [\n- [\n- \"7f3c9194.2bc928\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"c5bbfd9e.fdb5\",\n- \"type\": \"inject\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"\",\n- \"topic\": \"\",\n- \"payload\": \"\",\n- \"payloadType\": \"date\",\n- \"repeat\": \"\",\n- \"crontab\": \"\",\n- \"once\": false,\n- \"x\": 140,\n- \"y\": 520,\n- \"wires\": [\n- [\n- \"c3f15720.5a901\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"7855b2b8.0d1334\",\n- \"type\": \"comment\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"Override the current state node's pre-configured entity_id value\",\n- \"info\": \"\",\n- \"x\": 265,\n- \"y\": 300,\n- \"wires\": []\n- },\n- {\n- \"id\": \"4c8253e2.d560cc\",\n- \"type\": \"inject\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"Overide service data to turn on\",\n- \"topic\": \"\",\n- \"payload\": \"{\\\"data\\\":{\\\"topic\\\":\\\"dev/mqtt-dev-binary-sensor/state\\\",\\\"payload\\\":\\\"1\\\"}}\",\n- \"payloadType\": \"json\",\n- \"repeat\": \"\",\n- \"crontab\": \"\",\n- \"once\": false,\n- \"x\": 210,\n- \"y\": 390,\n- \"wires\": [\n- [\n- \"b3481b2.bb19068\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"7f3c9194.2bc928\",\n- \"type\": \"debug\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"\",\n- \"active\": true,\n- \"console\": \"false\",\n- \"complete\": \"true\",\n- \"x\": 670,\n- \"y\": 520,\n- \"wires\": []\n- },\n- {\n- \"id\": \"73e5fa98.c017fc\",\n- \"type\": \"server-state-changed\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"MQTT Binary Sensor State\",\n- \"server\": \"aedb3267.4ec5f8\",\n- \"entityidfilter\": \"binary_sensor.mqtt_dev_binary_sensor\",\n- \"haltifstate\": \"\",\n- \"x\": 500,\n- \"y\": 410,\n- \"wires\": [\n- [\n- \"306d8a57.83dd16\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"306d8a57.83dd16\",\n- \"type\": \"function\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"Display State\",\n- \"func\": \"const isOn = msg.payload === 'on';\\n\\nnode.status({ \\n fill: isOn ? 'green' : 'grey', \\n shape: isOn ? 'dot' : 'ring',\\n text: `Sensor is currently ${msg.payload}`\\n});\\nreturn msg;\",\n- \"outputs\": 1,\n- \"noerr\": 0,\n- \"x\": 760,\n- \"y\": 410,\n- \"wires\": [\n- []\n- ]\n- },\n- {\n- \"id\": \"685db7.9310f248\",\n- \"type\": \"comment\",\n- \"z\": \"ac309840.633668\",\n- \"name\": \"Use above to test the Halt If option\",\n- \"info\": \"\",\n- \"x\": 180,\n- \"y\": 470,\n- \"wires\": []\n- },\n- {\n- \"id\": \"5de16c5.c1e8814\",\n- \"type\": \"inject\",\n- \"z\": \"75d3404c.f8ea8\",\n- \"name\": \"Run\",\n- \"topic\": \"\",\n- \"payload\": \"\",\n- \"payloadType\": \"date\",\n- \"repeat\": \"\",\n- \"crontab\": \"\",\n- \"once\": false,\n- \"x\": 120,\n- \"y\": 100,\n- \"wires\": [\n- [\n- \"be0bec27.a621b\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"e7270836.6b9ae8\",\n- \"type\": \"debug\",\n- \"z\": \"75d3404c.f8ea8\",\n- \"name\": \"\",\n- \"active\": true,\n- \"console\": \"false\",\n- \"complete\": \"true\",\n- \"x\": 530,\n- \"y\": 100,\n- \"wires\": []\n- },\n- {\n- \"id\": \"4695013b.8efae8\",\n- \"type\": \"comment\",\n- \"z\": \"75d3404c.f8ea8\",\n- \"name\": \"Basic fetching of history returns all history from 1 day ago\",\n- \"info\": \"\",\n- \"x\": 240,\n- \"y\": 50,\n- \"wires\": []\n- },\n- {\n- \"id\": \"be0bec27.a621b\",\n- \"type\": \"api-get-history\",\n- \"z\": \"75d3404c.f8ea8\",\n- \"name\": \"History: No Config\",\n- \"server\": \"aedb3267.4ec5f8\",\n- \"startdate\": \"\",\n- \"x\": 320,\n- \"y\": 100,\n- \"wires\": [\n- [\n- \"e7270836.6b9ae8\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"137097f8.1a6018\",\n- \"type\": \"inject\",\n- \"z\": \"75d3404c.f8ea8\",\n- \"name\": \"Run\",\n- \"topic\": \"\",\n- \"payload\": \"\",\n- \"payloadType\": \"date\",\n- \"repeat\": \"\",\n- \"crontab\": \"\",\n- \"once\": false,\n- \"x\": 110,\n- \"y\": 220,\n- \"wires\": [\n- [\n- \"797864c8.ca55bc\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"26fd62e7.c1128e\",\n- \"type\": \"debug\",\n- \"z\": \"75d3404c.f8ea8\",\n- \"name\": \"\",\n- \"active\": true,\n- \"console\": \"false\",\n- \"complete\": \"true\",\n- \"x\": 810,\n- \"y\": 220,\n- \"wires\": []\n- },\n- {\n- \"id\": \"797864c8.ca55bc\",\n- \"type\": \"api-get-history\",\n- \"z\": \"75d3404c.f8ea8\",\n- \"name\": \"History: Default Date Set\",\n- \"server\": \"aedb3267.4ec5f8\",\n- \"startdate\": \"2018-01-29T13:00:00+00:00\",\n- \"x\": 590,\n- \"y\": 220,\n- \"wires\": [\n- [\n- \"26fd62e7.c1128e\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"1c9c989b.8123b7\",\n- \"type\": \"comment\",\n- \"z\": \"75d3404c.f8ea8\",\n- \"name\": \"Using pre-configured history and overrides\",\n- \"info\": \"\",\n- \"x\": 180,\n- \"y\": 180,\n- \"wires\": []\n- },\n- {\n- \"id\": \"165beefe.61ba81\",\n- \"type\": \"inject\",\n- \"z\": \"75d3404c.f8ea8\",\n- \"name\": \"Run\",\n- \"topic\": \"\",\n- \"payload\": \"\",\n- \"payloadType\": \"date\",\n- \"repeat\": \"\",\n- \"crontab\": \"\",\n- \"once\": false,\n- \"x\": 110,\n- \"y\": 300,\n- \"wires\": [\n- [\n- \"e01f3364.14f4a\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"e01f3364.14f4a\",\n- \"type\": \"function\",\n- \"z\": \"75d3404c.f8ea8\",\n- \"name\": \"Override startdate\",\n- \"func\": \"msg.startdate = (new Date()).toISOString();\\nreturn msg;\",\n- \"outputs\": 1,\n- \"noerr\": 0,\n- \"x\": 310,\n- \"y\": 300,\n- \"wires\": [\n- [\n- \"797864c8.ca55bc\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"731bf8e4.af1fc8\",\n- \"type\": \"comment\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"Incoming Events\",\n- \"info\": \"\",\n- \"x\": 100,\n- \"y\": 40,\n- \"wires\": []\n- },\n- {\n- \"id\": \"34acd979.07aba6\",\n- \"type\": \"comment\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"Fetching Data from Home Assistant\",\n- \"info\": \"\",\n- \"x\": 169,\n- \"y\": 251,\n- \"wires\": []\n- },\n- {\n- \"id\": \"22f35787.0c62f8\",\n- \"type\": \"comment\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"Calling Home Assistant Services\",\n- \"info\": \"\",\n- \"x\": 170,\n- \"y\": 520,\n- \"wires\": []\n- },\n- {\n- \"id\": \"8c8b3b61.9b4a28\",\n- \"type\": \"inject\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"Run\",\n- \"topic\": \"\",\n- \"payload\": \"\",\n- \"payloadType\": \"date\",\n- \"repeat\": \"\",\n- \"crontab\": \"\",\n- \"once\": false,\n- \"x\": 110,\n- \"y\": 600,\n- \"wires\": [\n- [\n- \"dd337e5e.fed47\"\n- ]\n- ]\n- },\n- {\n- \"id\": \"dd337e5e.fed47\",\n- \"type\": \"api-call-service\",\n- \"z\": \"a9b7da37.df64a8\",\n- \"name\": \"Set MQTT Binary sensor to off state\",\n- \"server\": \"aedb3267.4ec5f8\",\n- \"service_domain\": \"mqtt\",\n- \"service\": \"publish\",\n- \"data\": \"{\\\"topic\\\":\\\"dev/mqtt-dev-binary-sensor/state\\\",\\\"payload\\\":\\\"0\\\"}\",\n- \"x\": 430,\n- \"y\": 600,\n- \"wires\": []\n- }\n]\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "\"joi\": \"^13.1.1\",\n\"lodash.merge\": \"^4.6.0\",\n\"lowdb\": \"^1.0.0\",\n- \"node-home-assistant\": \"AYapejian/node-home-assistant#dev-master\",\n+ \"node-home-assistant\": \"0.2.1\",\n\"node-red\": \"node-red/node-red#0.18.2\",\n\"selectn\": \"^1.1.2\",\n\"serialize-javascript\": \"^1.4.0\",\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | upped node-home-assistant version to 0.2.1 |
748,240 | 16.02.2018 23:56:05 | 18,000 | a16acc5acd0ac07b57a1aa0fd94ec050c4b55471 | Added link to flows example | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "@@ -15,6 +15,8 @@ $ npm install node-red-contrib-home-assistant\n# then restart node-red\n```\n+For flow examples checkout the [flows here](https://raw.githubusercontent.com/AYapejian/node-red-contrib-home-assistant/master/_docker/node-red/root-fs/data/flows.json)\n+\n---\n## Included Nodes\nThe installed nodes have more detailed information in the node-red info pane shown when the node is selected. Below is a quick summary\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Added link to flows example |
748,241 | 11.02.2018 20:21:47 | 18,000 | 8f4a91523fbbed4a4aed1e543bd1c41eca42c75a | Preserve original msg object when passing through "current state" node | [
{
"change_type": "MODIFY",
"old_path": "nodes/api_current-state/api_current-state.js",
"new_path": "nodes/api_current-state/api_current-state.js",
"diff": "@@ -48,7 +48,10 @@ module.exports = function(RED) {\nreturn null;\n}\n- this.node.send({ topic: entity_id, payload: currentState.state, data: currentState });\n+ msg.topic = entity_id;\n+ msg.payload = currentState.state;\n+ msg.data = currentState;\n+ this.node.send(msg);\n}\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Preserve original msg object when passing through "current state" node |
748,241 | 28.02.2018 18:11:02 | 18,000 | 4bca63402bc709b9f6bf556c5f5b96f71a29c830 | Adjusted for 0.3.0: using message instead of msg | [
{
"change_type": "MODIFY",
"old_path": "nodes/api_current-state/api_current-state.js",
"new_path": "nodes/api_current-state/api_current-state.js",
"diff": "@@ -48,10 +48,10 @@ module.exports = function(RED) {\nreturn null;\n}\n- msg.topic = entity_id;\n- msg.payload = currentState.state;\n- msg.data = currentState;\n- this.node.send(msg);\n+ message.topic = entity_id;\n+ message.payload = currentState.state;\n+ message.data = currentState;\n+ this.node.send(message);\n}\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Adjusted for 0.3.0: using message instead of msg |
748,256 | 10.03.2018 13:13:51 | -3,600 | a401f894a9dd76aa3e91e362f861e04dd4a036f1 | Added try/catch in onHaEventsStateChanged | [
{
"change_type": "MODIFY",
"old_path": "nodes/server-events-state-changed/server-events-state-changed.js",
"new_path": "nodes/server-events-state-changed/server-events-state-changed.js",
"diff": "@@ -23,6 +23,7 @@ module.exports = function(RED) {\n}\nonHaEventsStateChanged (evt) {\n+ try {\nconst { entity_id, event } = evt;\nconst shouldHaltIfState = this.shouldHaltIfState(event);\n@@ -46,6 +47,9 @@ module.exports = function(RED) {\nthis.send(msg);\n}\n+ } catch (e) {\n+ this.error(e);\n+ }\n}\nshouldHaltIfState (haEvent, haltIfState) {\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Added try/catch in onHaEventsStateChanged |
748,262 | 27.03.2018 12:29:44 | 18,000 | 4c36223faf94ce4cf183428934c6cbb1a9f2e2dd | Update api_current-state.js | [
{
"change_type": "MODIFY",
"old_path": "nodes/api_current-state/api_current-state.js",
"new_path": "nodes/api_current-state/api_current-state.js",
"diff": "@@ -7,6 +7,8 @@ module.exports = function(RED) {\nconfig: {\nname: {},\nhalt_if: {},\n+ override_topic: {},\n+ override_payload: {},\nentity_id: {},\nserver: { isNode: true }\n},\n@@ -48,7 +50,27 @@ module.exports = function(RED) {\nreturn null;\n}\n- this.node.send({ topic: entity_id, payload: currentState.state, data: currentState });\n+ var override_topic = this.nodeConfig.override_topic;\n+ var override_payload = this.nodeConfig.override_payload;\n+\n+ //default switches to true if undefined (backward compatibility)\n+ if (this.nodeConfig.override_topic == null){\n+ override_topic = true;\n+ }\n+ if(this.nodeConfig.override_payload == null){\n+ override_payload = true;\n+ }\n+\n+ if(override_topic){\n+ message.topic = entity_id;\n+ }\n+\n+ if(override_payload){\n+ message.payload = currentState.state;\n+ }\n+\n+ message.data = currentState;\n+ this.node.send(message);\n}\n}\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Update api_current-state.js |
748,247 | 26.04.2018 11:19:11 | 25,200 | 8e1cc9ae81dc14ed858e253f674666c081ad0476 | Update README.md
credit author | [
{
"change_type": "MODIFY",
"old_path": "README.md",
"new_path": "README.md",
"diff": "+NOTE: I did not write this, I forked from [@AYapejian](https://github.com/AYapejian/node-red-contrib-home-assistant) due to a lack of responsiveness to issues and pull requests.\n+\n# Node Red Contrib Home Assistant\nVarious nodes to assist in setting up automation using [node-red](https://nodered.org/) communicating with [Home Assistant](https://home-assistant.io/).\n@@ -10,7 +12,7 @@ Project is going through active development and as such will probably have a few\nThis assumes you have [node-red](http://nodered.org/) already installed and working, if you need to install node-red see [here](http://nodered.org/docs/getting-started/installation)\n-NOTE: node-red-contrib-home-assistant requires node.JS > 8.0 If you're running Node-Red in Docker you'll need to pull the -v8 image for this to work.\n+#### NOTE: node-red-contrib-home-assistant requires node.JS > 8.0 If you're running Node-Red in Docker you'll need to pull the -v8 image for this to work.\n```shell\n$ cd cd ~/.node-red\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Update README.md
credit author |
748,247 | 26.04.2018 16:16:42 | 25,200 | 9db8b2df0a3a02ee37a8bfb72e2ee6485b3c98da | first attempt at status message | [
{
"change_type": "MODIFY",
"old_path": "nodes/api_call-service/api_call-service.js",
"new_path": "nodes/api_call-service/api_call-service.js",
"diff": "@@ -49,7 +49,7 @@ module.exports = function(RED) {\nif (!apiService) throw new Error('call service node is missing api \"service\" property, not found in config or payload');\nthis.debug(`Calling Service: ${apiDomain}:${apiService} -- ${JSON.stringify(apiData || {})}`);\n-\n+ this.status({fill:\"green\",shape:\"dot\",text: 'called'});\nthis.send({\npayload: {\ndomain: apiDomain,\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/api_current-state/api_current-state.js",
"new_path": "nodes/api_current-state/api_current-state.js",
"diff": "@@ -40,6 +40,7 @@ module.exports = function(RED) {\nif (!states) return logAndContinueEmpty('local state cache missing, sending empty payload');\nconst currentState = states[entity_id];\n+ this.status({fill:\"green\",shape:\"dot\",text: `State: ${currentState.state} at${Date()}`}) // ${getMonth() getDate() getHour():getMinute()});\nif (!currentState) return logAndContinueEmpty(`entity could not be found in cache for entity_id: ${entity_id}, sending empty payload`);\nconst shouldHaltIfState = this.nodeConfig.halt_if && (currentState.state === this.nodeConfig.halt_if);\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | first attempt at status message |
748,240 | 27.04.2018 10:47:26 | 14,400 | 29a3df548b31e318f849b2fb057cce33f0a56448 | Fixing bug with docker-compose due to directory naming, invalid reference error due to beginning | [
{
"change_type": "MODIFY",
"old_path": ".gitignore",
"new_path": ".gitignore",
"diff": "@@ -7,3 +7,4 @@ _scratchpad_flows\n.DS_Store\n_docker-volumes/\n./package-lock.json\n+*.log\n"
},
{
"change_type": "DELETE",
"old_path": "_docker/config.env",
"new_path": null,
"diff": "-NODE_ENV=development\n-DEBUG=home-assistant*\n-\n-HA_HOME_ASSISTANT_TIME_ZONE=America/New_York\n-HA_HOME_ASSISTANT_LATITUDE=42.360082\n-HA_HOME_ASSISTANT_LONGITUDE=-71.058880\n-HA_HOME_ASSISTANT_ELEVATION=38\n-HA_HOME_ASSISTANT_TEMPERATURE_UNIT=F\n-HA_HOME_ASSISTANT_UNIT_SYSTEM=imperial\n-\n-HA_MQTT_CLIENT_ID=home-assistant-dev\n-\n-HA_HTTP_API_PASSWORD=password\n-HA_LOGGER_DEFAULT=info\n-\n-NODE_RED_URL=http://localhost:1880\n"
},
{
"change_type": "DELETE",
"old_path": "_docker/home-assistant/Dockerfile",
"new_path": null,
"diff": "-FROM homeassistant/home-assistant:0.62.0\n-\n-COPY root-fs /\n-\n-CMD [ \"python\", \"-m\", \"homeassistant\", \"--config\", \"/config\" ]\n"
},
{
"change_type": "DELETE",
"old_path": "_docker/mqtt/Dockerfile",
"new_path": null,
"diff": "-FROM eclipse-mosquitto:1.4.12\n-\n-COPY root-fs /\n-\n-# Install mosquitto_pub and mosquitto_sub, link as shorthand pub/sub\n-RUN apk add --no-cache mosquitto-clients \\\n- && ln -s /usr/bin/mosquitto_pub /usr/local/bin/pub \\\n- && ln -s /usr/bin/mosquitto_sub /usr/local/bin/sub\n"
},
{
"change_type": "DELETE",
"old_path": "_docker/mqtt/root-fs/dev-binary-sensor.sh",
"new_path": null,
"diff": "-while sleep $MQTT_DEV_BINARY_SENSOR_INTERVAL; do\n- random_on_off=$(( RANDOM % 2 ))\n- mosquitto_pub -h $MQTT_HOST -p $MQTT_PORT -m $random_on_off -t $MQTT_DEV_BINARY_SENSOR_TOPIC\n-done\n"
},
{
"change_type": "DELETE",
"old_path": "_docker/mqtt/root-fs/dev-sensor.sh",
"new_path": null,
"diff": "-while sleep $MQTT_DEV_SENSOR_INTERVAL; do\n- random_num=`od -A n -t d -N 1 /dev/urandom |tr -d ' '`\n- mosquitto_pub -h $MQTT_HOST -p $MQTT_PORT -m $random_num -t $MQTT_DEV_SENSOR_TOPIC\n-done\n"
},
{
"change_type": "DELETE",
"old_path": "_docker/mqtt/root-fs/listener-cmd.sh",
"new_path": null,
"diff": "-#!/bin/sh\n-\n-mosquitto_sub -v -h $MQTT_HOST -p $MQTT_PORT -t $MQTT_LISTENER_TOPIC\n"
},
{
"change_type": "RENAME",
"old_path": "_docker/docker-compose.mapped.yml",
"new_path": "docker/docker-compose.mapped.yml",
"diff": "@@ -26,6 +26,4 @@ services:\nports:\n- 8300:8300\n- 8123:8123\n- depends_on:\n- - mqtt\n"
},
{
"change_type": "RENAME",
"old_path": "_docker/docker-compose.yml",
"new_path": "docker/docker-compose.yml",
"diff": "-version: '3.1'\n+version: '3'\nservices:\nnode-red:\n- env_file: ./config.env\nbuild: ./node-red\ncommand: npm run dev:watch\nvolumes:\n@@ -13,7 +12,6 @@ services:\n- 9123:9229\nhome-assistant:\n- env_file: ./config.env\nbuild: ./home-assistant\n# While messing with HA config map the repo config to the container for easy changes\nvolumes:\n@@ -21,4 +19,3 @@ services:\nports:\n- 8300:8300\n- 8123:8123\n-\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "docker/home-assistant/Dockerfile",
"diff": "+FROM homeassistant/home-assistant:0.67.1\n+\n+ENV HA_HOME_ASSISTANT_TIME_ZONE=America/New_York \\\n+ HA_HOME_ASSISTANT_LATITUDE=42.360082 \\\n+ HA_HOME_ASSISTANT_LONGITUDE=-71.058880 \\\n+ HA_HOME_ASSISTANT_ELEVATION=38 \\\n+ HA_HOME_ASSISTANT_TEMPERATURE_UNIT=F \\\n+ HA_HOME_ASSISTANT_UNIT_SYSTEM=imperial \\\n+ HA_HTTP_API_PASSWORD=password \\\n+ HA_LOGGER_DEFAULT=info \\\n+ NODE_RED_URL=http://localhost:1880/\n+\n+COPY root-fs /\n+\n+CMD [ \"python\", \"-m\", \"homeassistant\", \"--config\", \"/config\" ]\n"
},
{
"change_type": "RENAME",
"old_path": "_docker/home-assistant/root-fs/config/configuration.yaml",
"new_path": "docker/home-assistant/root-fs/config/configuration.yaml",
"diff": "@@ -34,15 +34,54 @@ panel_iframe:\nurl: !env_var NODE_RED_URL\nicon: mdi:grid-on\n-# Test Entities for Development\n-# automation:\n-# initial_state: True\n-# trigger:\n-# platform: time\n-# seconds: '/10'\n-# action:\n-# service: switch.toggle\n-# entity_id: light.kitchen_light\n+\n+alarm_control_panel:\n+ - platform: demo\n+\n+binary_sensor:\n+ - platform: demo\n+\n+camera:\n+ - platform: demo\n+\n+climate:\n+ - platform: demo\n+\n+cover:\n+ - platform: demo\n+\n+fan:\n+ - platform: demo\n+\n+image_processing:\n+ - platform: demo\n+\n+light:\n+ - platform: demo\n+\n+lock:\n+ - platform: demo\n+\n+notify:\n+ - platform: demo\n+\n+remote:\n+ - platform: demo\n+\n+sensor:\n+ - platform: demo\n+\n+switch:\n+ - platform: demo\n+\n+tts:\n+ - platform: demo\n+\n+weather:\n+ - platform: demo\n+\n+mailbox:\n+ - platform: demo\ninput_select:\ntime_of_day:\n@@ -78,3 +117,13 @@ input_datetime:\nname: Input with only time\nhas_date: false\nhas_time: true\n+\n+# Test Entities for Development\n+# automation:\n+# initial_state: True\n+# trigger:\n+# platform: time\n+# seconds: '/10'\n+# action:\n+# service: switch.toggle\n+# entity_id: light.kitchen_light\n"
},
{
"change_type": "RENAME",
"old_path": "_docker/node-red/Dockerfile",
"new_path": "docker/node-red/Dockerfile",
"diff": "@@ -18,9 +18,11 @@ EXPOSE 1880\nEXPOSE 9229\n# Environment variable holding file path for flows configuration\n-ENV USER_DIR=/data\n-ENV FLOWS=flows.json\n-ENV NODE_PATH=/app/node_modules:/data/node_modules\n-ENV NODEMON_CONFIG=/app/nodemon.json\n+ENV USER_DIR=/data \\\n+ FLOWS=flows.json \\\n+ NODE_PATH=/app/node_modules:/data/node_modules \\\n+ NODEMON_CONFIG=/app/nodemon.json \\\n+ NODE_ENV=development \\\n+ DEBUG=home-assistant*\nCMD [\"npm\", \"start\"]\n"
},
{
"change_type": "RENAME",
"old_path": "_docker/node-red/root-fs/app/nodemon.json",
"new_path": "docker/node-red/root-fs/app/nodemon.json",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "_docker/node-red/root-fs/app/package.json",
"new_path": "docker/node-red/root-fs/app/package.json",
"diff": "\"dev:watch\": \"/app/node_modules/.bin/nodemon --config $NODEMON_CONFIG --exec 'sleep 0.5; node --inspect=0.0.0.0:9229 /app/node_modules/node-red/red.js -v --userDir $USER_DIR $FLOWS'\"\n},\n\"dependencies\": {\n- \"node-red\": \"0.18.2\",\n+ \"node-red\": \"0.18.4\",\n\"node-red-contrib-contextbrowser\": \"*\",\n\"nodemon\": \"1.14.11\"\n},\n"
},
{
"change_type": "RENAME",
"old_path": "_docker/node-red/root-fs/data/flows.json",
"new_path": "docker/node-red/root-fs/data/flows.json",
"diff": ""
},
{
"change_type": "RENAME",
"old_path": "_docker/node-red/root-fs/data/package.json",
"new_path": "docker/node-red/root-fs/data/package.json",
"diff": ""
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Fixing bug with docker-compose due to directory naming, invalid reference error due to beginning |
748,247 | 27.04.2018 11:45:44 | 25,200 | 0c2f61523971467bb33498a532a8452acd12ff44 | Continued work on status message timestamps | [
{
"change_type": "MODIFY",
"old_path": "nodes/api_call-service/api_call-service.js",
"new_path": "nodes/api_call-service/api_call-service.js",
"diff": "@@ -49,7 +49,9 @@ module.exports = function(RED) {\nif (!apiService) throw new Error('call service node is missing api \"service\" property, not found in config or payload');\nthis.debug(`Calling Service: ${apiDomain}:${apiService} -- ${JSON.stringify(apiData || {})}`);\n- this.status({fill:\"green\",shape:\"dot\",text: 'called'});\n+ var todaysDate = new Date()\n+ var prettyDate = todaysDate.toLocaleDateString(\"en-US\",{month: 'short', day: 'numeric', hour12: false, hour: 'numeric', minute: 'numeric'});\n+ this.status({fill:\"green\",shape:\"dot\",text:`${apiDomain}.${apiService} called at: ${prettyDate}`});\nthis.send({\npayload: {\ndomain: apiDomain,\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/api_current-state/api_current-state.js",
"new_path": "nodes/api_current-state/api_current-state.js",
"diff": "@@ -40,7 +40,9 @@ module.exports = function(RED) {\nif (!states) return logAndContinueEmpty('local state cache missing, sending empty payload');\nconst currentState = states[entity_id];\n- this.status({fill:\"green\",shape:\"dot\",text: `State: ${currentState.state} at${Date()}`}) // ${getMonth() getDate() getHour():getMinute()});\n+ var todaysDate = new Date()\n+ var prettyDate = todaysDate.toLocaleDateString(\"en-US\",{month: 'short', day: 'numeric', hour12: false, hour: 'numeric', minute: 'numeric'});\n+ this.status({fill:\"green\",shape:\"dot\",text:`${currentState.state} at: ${prettyDate}`});\nif (!currentState) return logAndContinueEmpty(`entity could not be found in cache for entity_id: ${entity_id}, sending empty payload`);\nconst shouldHaltIfState = this.nodeConfig.halt_if && (currentState.state === this.nodeConfig.halt_if);\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/api_get-history/api_get-history.js",
"new_path": "nodes/api_get-history/api_get-history.js",
"diff": "@@ -37,10 +37,12 @@ module.exports = function(RED) {\nmessage.startdate = startdate;\nmessage.payload = res;\nthis.send(message);\n+ this.status({fill:\"green\",shape:\"dot\",text:\"Success\"});\n})\n.catch(err => {\nthis.warn('Error calling service, home assistant api error', err);\nthis.error('Error calling service, home assistant api error', message);\n+ this.status({fill:\"red\",shape:\"ring\",text:\"Error\"});\n});\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/api_render-template/api_render-template.js",
"new_path": "nodes/api_render-template/api_render-template.js",
"diff": "@@ -32,9 +32,11 @@ module.exports = function(RED) {\nmessage.template = template;\nmessage.payload = res;\nthis.send(message);\n+ this.status({fill:\"green\",shape:\"dot\",text:\"Success\"});\n})\n.catch(err => {\nthis.error(`Error calling service, home assistant api error: ${err.message}`, message);\n+ this.status({fill:\"red\",shape:\"ring\",text:\"Error\"});\n});\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "nodes/server-events-state-changed/server-events-state-changed.js",
"new_path": "nodes/server-events-state-changed/server-events-state-changed.js",
"diff": "@@ -31,6 +31,9 @@ module.exports = function(RED) {\nif (shouldHaltIfState) {\nthis.debug('flow halted due to \"halt if state\" setting');\n+ var todaysDate = new Date()\n+ var prettyDate = todaysDate.toLocaleDateString(\"en-US\",{month: 'short', day: 'numeric', hour12: false, hour: 'numeric', minute: 'numeric'});\n+ this.status({fill:\"yellow\",shape:\"ring\",text:`Halted: Event: ${event} at: ${prettyDate}'});\nreturn null;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "package.json",
"new_path": "package.json",
"diff": "{\n\"name\": \"node-red-contrib-home-assistant\",\n\"description\": \"node-red nodes to visually construct home automation with home assistant\",\n- \"version\": \"0.3.0\",\n+ \"version\": \"0.3.1\",\n\"homepage\": \"https://github.com/AYapejian/node-red-contrib-home-assistant\",\n\"bugs\": {\n\"url\": \"https://github.com/AYapejian/node-red-contrib-home-assistant/issues\"\n"
}
] | TypeScript | MIT License | zachowj/node-red-contrib-home-assistant-websocket | Continued work on status message timestamps |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.