├── .env ├── .gitignore ├── LICENSE ├── Procfile ├── README.md ├── django_iot ├── __init__.py ├── apps │ ├── __init__.py │ ├── devices │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_device_manufacturer_id.py │ │ │ └── __init__.py │ │ ├── models.py │ │ └── tests │ │ │ ├── __init__.py │ │ │ └── test_models.py │ ├── interactions │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── management │ │ │ ├── __init__.py │ │ │ └── commands │ │ │ │ ├── __init__.py │ │ │ │ └── interact.py │ │ ├── migrations │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_auto_20160326_1906.py │ │ │ ├── 0003_auto_20160326_1923.py │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── schedule.py │ │ ├── tasks.py │ │ ├── tests │ │ │ ├── __init__.py │ │ │ ├── test_management_commands.py │ │ │ └── test_tasks.py │ │ └── views.py │ ├── lifx │ │ ├── __init__.py │ │ ├── client.py │ │ ├── colors.py │ │ └── tests.py │ └── observations │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── 0002_color.py │ │ ├── 0003_auto_20160326_2228.py │ │ └── __init__.py │ │ ├── models.py │ │ └── tests │ │ ├── __init__.py │ │ └── test_models.py ├── celery.py ├── settings │ ├── __init__.py │ ├── common.py │ ├── dev.py │ └── production.py ├── static │ ├── humans.txt │ └── js │ │ └── bootstrap.min.js ├── templates │ ├── base.html │ └── index.html ├── urls.py └── wsgi.py ├── manage.py ├── requirements.txt └── runtime.txt /.env: -------------------------------------------------------------------------------- 1 | WEB_CONCURRENCY=2 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | venv 2 | *.pyc 3 | staticfiles -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: gunicorn django_iot.wsgi --log-file - 2 | scheduler: celery worker -B -A django_iot -l info 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Django for IoT 2 | 3 | This is the demo to accompany my talk on [Django for IoT](https://djangocon.eu/speakers/9) at DjangoCon Europe 2016. 4 | It controls an LIFX light bulb based on Twitter voting. 5 | 6 | You can fork this to play around with your own projects, or get started fresh with https://github.com/aschn/cookiecutter-django-iot 7 | 8 | # Get started 9 | 10 | ## LIFX setup 11 | 12 | LIFX_TOKEN: get from https://cloud.lifx.com/ 13 | 14 | 15 | ## Twitter setup 16 | 17 | Sign into https://apps.twitter.com/ with your twitter account, and click "create new app" 18 | 19 | 20 | ## Run locally 21 | 22 | ``` 23 | export DATABASE_URL=postgres://localhost/mydbname 24 | export SECRET_KEY=[your value] 25 | export LIFX_TOKEN=[your value] 26 | export TWITTER_CONSUMER_KEY=[your value] 27 | export TWITTER_CONSUMER_SECRET=[your value] 28 | export TWITTER_ACCESS_TOKEN=[your value] 29 | export TWITTER_ACCESS_SECRET=[your value] 30 | export VOTE_HASHTAG=[your hashtag] 31 | createdb mydbname 32 | python manage.py migrate 33 | python manage.py createsuperuser 34 | python manage.py runserver 35 | ``` 36 | 37 | log into localhost:8000/admin 38 | 39 | click on Device and add a device 40 | 41 | or in a python terminal: 42 | 43 | ``` 44 | from django_iot.apps.lifx import client 45 | client.configure_devices() 46 | ``` 47 | 48 | ## Deployment to Heroku 49 | 50 | $ git init 51 | $ git add -A 52 | $ git commit -m "Initial commit" 53 | 54 | $ heroku create 55 | $ git push heroku master 56 | 57 | $ heroku run python manage.py migrate 58 | 59 | 60 | to use management commands: 61 | ``` 62 | heroku addons:create scheduler:standard 63 | ``` 64 | 65 | 66 | celery resources: 67 | * https://www.cloudamqp.com/docs/celery.html 68 | * https://library.launchkit.io/three-quick-tips-from-two-years-with-celery-c05ff9d7f9eb#.e3a9mgoud 69 | * https://realpython.com/blog/python/asynchronous-tasks-with-django-and-celery/ 70 | * https://devcenter.heroku.com/articles/celery-heroku#celery-and-django 71 | -------------------------------------------------------------------------------- /django_iot/__init__.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | # This will make sure the app is always imported when 4 | # Django starts so that shared_task will use this app. 5 | from .celery import app as celery_app # noqa 6 | -------------------------------------------------------------------------------- /django_iot/apps/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/apps/__init__.py -------------------------------------------------------------------------------- /django_iot/apps/devices/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/apps/devices/__init__.py -------------------------------------------------------------------------------- /django_iot/apps/devices/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django_iot.apps.devices.models import Device 3 | 4 | 5 | class DeviceAdmin(admin.ModelAdmin): 6 | list_display = ('id', 'name', 'device_type', 'location') 7 | list_filter = ('device_type', 'location') 8 | 9 | 10 | admin.site.register(Device, DeviceAdmin) 11 | -------------------------------------------------------------------------------- /django_iot/apps/devices/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import migrations, models 5 | 6 | 7 | class Migration(migrations.Migration): 8 | 9 | dependencies = [ 10 | ] 11 | 12 | operations = [ 13 | migrations.CreateModel( 14 | name='Device', 15 | fields=[ 16 | ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), 17 | ('created_at', models.DateTimeField(auto_now_add=True)), 18 | ('updated_at', models.DateTimeField(auto_now=True)), 19 | ('name', models.CharField(max_length=100)), 20 | ('device_type', models.CharField(max_length=100)), 21 | ('location', models.CharField(max_length=100)), 22 | ], 23 | ), 24 | ] 25 | -------------------------------------------------------------------------------- /django_iot/apps/devices/migrations/0002_device_manufacturer_id.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.4 on 2016-03-05 23:25 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | ('devices', '0001_initial'), 12 | ] 13 | 14 | operations = [ 15 | migrations.AddField( 16 | model_name='device', 17 | name='manufacturer_id', 18 | field=models.CharField(default=0, max_length=100, unique=True), 19 | preserve_default=False, 20 | ), 21 | ] 22 | -------------------------------------------------------------------------------- /django_iot/apps/devices/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/apps/devices/migrations/__init__.py -------------------------------------------------------------------------------- /django_iot/apps/devices/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class Device(models.Model): 5 | # created and updated 6 | created_at = models.DateTimeField(auto_now_add=True) 7 | updated_at = models.DateTimeField(auto_now=True) 8 | 9 | # device name 10 | name = models.CharField(max_length=100) 11 | 12 | # manufacturer's id 13 | manufacturer_id = models.CharField(max_length=100, unique=True) 14 | 15 | # type, brand name, etc 16 | # you may want to add choices to this 17 | device_type = models.CharField(max_length=100) 18 | 19 | # location 20 | # you may want to add choices to this 21 | location = models.CharField(max_length=100) 22 | 23 | def __str__(self): 24 | return self.name 25 | -------------------------------------------------------------------------------- /django_iot/apps/devices/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/apps/devices/tests/__init__.py -------------------------------------------------------------------------------- /django_iot/apps/devices/tests/test_models.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | from django_iot.apps.devices.models import Device 3 | 4 | 5 | class TestDevice(TestCase): 6 | def setUp(self): 7 | self.device = Device.objects.create(name='my toi', 8 | device_type='TOI', 9 | location='robohome', 10 | manufacturer_id='0101') 11 | 12 | def test_dates(self): 13 | self.assertGreater(self.device.updated_at, 14 | self.device.created_at) 15 | 16 | def test_str(self): 17 | self.assertEqual(str(self.device), self.device.name) 18 | -------------------------------------------------------------------------------- /django_iot/apps/interactions/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/apps/interactions/__init__.py -------------------------------------------------------------------------------- /django_iot/apps/interactions/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django_iot.apps.interactions.models import TwitterVote 3 | 4 | 5 | class TwitterVoteAdmin(admin.ModelAdmin): 6 | list_display = ['created_at', 'hashtag', 'winner', 'n_votes_winner', 'n_votes_total'] 7 | 8 | 9 | admin.site.register(TwitterVote, TwitterVoteAdmin) 10 | -------------------------------------------------------------------------------- /django_iot/apps/interactions/management/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/apps/interactions/management/__init__.py -------------------------------------------------------------------------------- /django_iot/apps/interactions/management/commands/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/apps/interactions/management/commands/__init__.py -------------------------------------------------------------------------------- /django_iot/apps/interactions/management/commands/interact.py: -------------------------------------------------------------------------------- 1 | from django.core.management.base import BaseCommand 2 | from django_iot.apps.interactions import tasks 3 | 4 | 5 | class Command(BaseCommand): 6 | help = 'Run an interaction task' 7 | 8 | def add_arguments(self, parser): 9 | parser.add_argument('task_name') 10 | parser.add_argument('--device_id', required=False, type=int) 11 | parser.add_argument('--is_on', required=False, type=bool) 12 | parser.add_argument('--color', required=False, type=str) 13 | parser.add_argument('--brightness', required=False, type=float) 14 | parser.add_argument('--hashtag', required=False, type=str) 15 | parser.add_argument('--votechoices', required=False, type=str, 16 | help='comma-separated list, eg red,blue,yellow') 17 | 18 | def handle(self, *args, **options): 19 | # get task 20 | task_fn = getattr(tasks, options['task_name']) 21 | 22 | # parse args 23 | try: 24 | options['votechoices'] = options['votechoices'].split(',') 25 | except AttributeError: # None if not provided 26 | options.pop('votechoices') 27 | 28 | # run task with args 29 | result = task_fn(**options) 30 | self.stdout.write('Ran %s with result %s' % (options['task_name'], result)) 31 | -------------------------------------------------------------------------------- /django_iot/apps/interactions/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.2 on 2016-03-26 18:57 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | initial = True 11 | 12 | dependencies = [ 13 | ] 14 | 15 | operations = [ 16 | migrations.CreateModel( 17 | name='TwitterVote', 18 | fields=[ 19 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 20 | ('created_at', models.DateTimeField(auto_now=True)), 21 | ('winner', models.CharField(blank=True, choices=[(b'white', b'white'), (b'red', b'red'), (b'orange', b'orange'), (b'yellow', b'yellow'), (b'cyan', b'cyan'), (b'green', b'green'), (b'blue', b'blue'), (b'purple', b'purple'), (b'pink', b'pink')], max_length=20, null=True)), 22 | ('hashtag', models.CharField(blank=True, max_length=50, null=True)), 23 | ('n_votes_winner', models.IntegerField(default=0)), 24 | ('n_votes_total', models.IntegerField(default=0)), 25 | ('log', models.TextField(blank=True, editable=False, null=True)), 26 | ], 27 | ), 28 | ] 29 | -------------------------------------------------------------------------------- /django_iot/apps/interactions/migrations/0002_auto_20160326_1906.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.2 on 2016-03-26 19:06 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | ('interactions', '0001_initial'), 12 | ] 13 | 14 | operations = [ 15 | migrations.AlterField( 16 | model_name='twittervote', 17 | name='log', 18 | field=models.TextField(default=b'', editable=False), 19 | ), 20 | ] 21 | -------------------------------------------------------------------------------- /django_iot/apps/interactions/migrations/0003_auto_20160326_1923.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.2 on 2016-03-26 19:23 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | ('interactions', '0002_auto_20160326_1906'), 12 | ] 13 | 14 | operations = [ 15 | migrations.AddField( 16 | model_name='twittervote', 17 | name='tally', 18 | field=models.CommaSeparatedIntegerField(default='', max_length=50), 19 | preserve_default=False, 20 | ), 21 | migrations.AlterField( 22 | model_name='twittervote', 23 | name='log', 24 | field=models.TextField(default=b''), 25 | ), 26 | migrations.AlterField( 27 | model_name='twittervote', 28 | name='winner', 29 | field=models.CharField(blank=True, choices=[(b'red', b'red'), (b'orange', b'orange'), (b'yellow', b'yellow'), (b'cyan', b'cyan'), (b'green', b'green'), (b'blue', b'blue'), (b'purple', b'purple'), (b'pink', b'pink')], max_length=20, null=True), 30 | ), 31 | ] 32 | -------------------------------------------------------------------------------- /django_iot/apps/interactions/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/apps/interactions/migrations/__init__.py -------------------------------------------------------------------------------- /django_iot/apps/interactions/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | import tweepy 3 | import os 4 | 5 | 6 | class TwitterVote(models.Model): 7 | # created time 8 | created_at = models.DateTimeField(auto_now=True) 9 | 10 | # winning choice 11 | VOTE_CHOICE_LIST = [ 12 | 'red', 'orange', 'yellow', 'cyan', 13 | 'green', 'blue', 'purple', 'pink' 14 | ] 15 | VOTE_CHOICE_TUPLES = [(x, x) for x in VOTE_CHOICE_LIST] 16 | winner = models.CharField(max_length=20, choices=VOTE_CHOICE_TUPLES, 17 | null=True, blank=True) 18 | 19 | # hashtag for voting 20 | hashtag = models.CharField(max_length=50, blank=True, null=True) 21 | 22 | # number of total and winning votes 23 | n_votes_winner = models.IntegerField(default=0) 24 | n_votes_total = models.IntegerField(default=0) 25 | 26 | # vote tally 27 | tally = models.CommaSeparatedIntegerField(max_length=50) 28 | 29 | # vote logs 30 | log = models.TextField(default='') 31 | 32 | # line separator 33 | LOG_LINE_SEP = '{{{{LINESEP}}}}' 34 | 35 | def collect_votes(self): 36 | # set up twitter 37 | auth = tweepy.OAuthHandler( 38 | os.environ.get('TWITTER_CONSUMER_KEY'), 39 | os.environ.get('TWITTER_CONSUMER_SECRET')) 40 | auth.set_access_token( 41 | os.environ.get('TWITTER_ACCESS_TOKEN'), 42 | os.environ.get('TWITTER_ACCESS_SECRET'), 43 | ) 44 | api = tweepy.API(auth) 45 | 46 | # search for hashtag 47 | results = api.search(q=self.hashtag, rpp=100) 48 | 49 | # collect votes 50 | vote_counts = {choice: 0 for choice in self.VOTE_CHOICE_LIST} 51 | log_entries = [] 52 | for tweet in results: 53 | for choice in self.VOTE_CHOICE_LIST: 54 | if choice in tweet.text: 55 | # increment vote 56 | vote_counts[choice] += 1 57 | 58 | # store log 59 | log_entry = 'at %s @%s voted for %s\n%s' % ( 60 | tweet.created_at, tweet.user.screen_name, 61 | choice, tweet.text 62 | ) 63 | log_entries.append(log_entry) 64 | 65 | # store winner and tallies 66 | self.winner, self.n_votes_winner = max(vote_counts.iteritems(), key=lambda x: x[1]) 67 | self.n_votes_total = sum(vote_counts.values()) 68 | self.tally = ','.join([str(vote_counts[choice]) for choice in self.VOTE_CHOICE_LIST]) 69 | self.log = self.LOG_LINE_SEP.join(log_entries) 70 | 71 | # save 72 | self.save() 73 | 74 | # return winner and winning fraction 75 | try: 76 | return self.winner, self.n_votes_winner / float(self.n_votes_total) 77 | except ZeroDivisionError: 78 | return None, None 79 | -------------------------------------------------------------------------------- /django_iot/apps/interactions/schedule.py: -------------------------------------------------------------------------------- 1 | from celery.schedules import crontab 2 | 3 | 4 | SCHEDULE = { 5 | 'refresh_all': { 6 | 'task': 'django_iot.apps.interactions.tasks.refresh_all', 7 | 'schedule': crontab(minute='*/5') 8 | }, 9 | 'vote_red': { 10 | 'task': 'django_iot.apps.interactions.tasks.run_twitter_vote', 11 | 'schedule': crontab(minute='*/5'), 12 | 'kwargs': {'device_id': 1} 13 | }, 14 | } 15 | -------------------------------------------------------------------------------- /django_iot/apps/interactions/tasks.py: -------------------------------------------------------------------------------- 1 | from django.utils import timezone 2 | from django_iot.apps.devices.models import Device 3 | from django_iot.apps.lifx import client 4 | from django_iot.apps.interactions.models import TwitterVote 5 | from celery import shared_task 6 | import os 7 | 8 | 9 | @shared_task 10 | def pull_attributes(device_id=None, **kwargs): 11 | """ 12 | Pulls attribute data from the device vendor's API, 13 | stores the attributes in the database, 14 | and returns the pks of the attributes. 15 | """ 16 | # check device exists 17 | device = Device.objects.get(pk=device_id) 18 | 19 | # fetch attributes 20 | data = client.get_attributes(device_id) 21 | 22 | # create observations 23 | pks = [] 24 | for units, value in data.iteritems(): 25 | obs = device.attribute_set.create( 26 | valid_at=timezone.now(), 27 | value=value, 28 | units=units, 29 | ) 30 | pks.append(obs.pk) 31 | 32 | # return pk 33 | return pks 34 | 35 | 36 | @shared_task 37 | def pull_status(device_id=None, **kwargs): 38 | """ 39 | Pulls the current device status from the device vendor's API, 40 | stores the status in the database, 41 | and returns the pks of the status. 42 | """ 43 | # check device exists 44 | device = Device.objects.get(pk=device_id) 45 | 46 | # fetch status 47 | status_message = client.get_status(device_id) 48 | 49 | # create status 50 | if status_message == 'on': 51 | is_on = True 52 | else: 53 | is_on = False 54 | status = device.powerstatus_set.create( 55 | valid_at=timezone.now(), 56 | is_on=is_on, 57 | ) 58 | 59 | # return pk 60 | return [status.pk] 61 | 62 | 63 | @shared_task 64 | def refresh_all(**kwargs): 65 | """ 66 | Refreshes data and status for all devices 67 | """ 68 | for device in Device.objects.all(): 69 | pull_status(device.pk) 70 | pull_attributes(device.pk) 71 | 72 | 73 | @shared_task 74 | def set_status(device_id=None, is_on=True, **kwargs): 75 | """ 76 | Sets the device status using the device vendor's API, 77 | stores the new status in the database, 78 | and returns the pks of the status. 79 | """ 80 | # check device exists 81 | device = Device.objects.get(pk=device_id) 82 | 83 | # turn on or off 84 | if is_on: 85 | result = client.turn_on(device_id) 86 | else: 87 | result = client.turn_off(device_id) 88 | 89 | # create status 90 | if result['status'] == 'ok': 91 | status = device.powerstatus_set.create( 92 | valid_at=timezone.now(), 93 | is_on=is_on, 94 | ) 95 | 96 | # return pk 97 | return [status.pk] 98 | else: 99 | return [] 100 | 101 | 102 | @shared_task 103 | def set_attributes(device_id=None, **kwargs): 104 | """ 105 | Sets the device attributes using the device vendor's API, 106 | stores the new attributes in the database, 107 | and returns the pks of the attributes. 108 | """ 109 | # set attributes 110 | client.set_color(device_id, **kwargs) 111 | 112 | # log by pulling fresh data 113 | return pull_attributes(device_id) 114 | 115 | 116 | @shared_task 117 | def run_twitter_vote(device_id=None, hashtag=None, 118 | **kwargs): 119 | # use default hashtag if none given 120 | if not hashtag: 121 | hashtag = os.environ.get('VOTE_HASHTAG') 122 | 123 | # run voting 124 | voter = TwitterVote.objects.create(hashtag=hashtag) 125 | top_choice, brightness = voter.collect_votes() 126 | 127 | # set color based on top vote 128 | return set_attributes(device_id, color=top_choice, brightness=brightness) 129 | -------------------------------------------------------------------------------- /django_iot/apps/interactions/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/apps/interactions/tests/__init__.py -------------------------------------------------------------------------------- /django_iot/apps/interactions/tests/test_management_commands.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | from django.core.management import call_command 3 | from django_iot.apps.devices.models import Device 4 | from StringIO import StringIO 5 | from mock import patch 6 | 7 | 8 | class TestPullStatus(TestCase): 9 | def setUp(self): 10 | self.device1 = Device.objects.create(manufacturer_id=1) 11 | self.device2 = Device.objects.create(manufacturer_id=2) 12 | 13 | self.stdout = StringIO() 14 | 15 | @patch('django_iot.apps.interactions.tasks.client.get_status') 16 | def test_pull_one(self, mock_method): 17 | mock_method.return_value = 'on' 18 | 19 | # call command for one 20 | call_command('interact', 'pull_status', 21 | device_id=self.device1.pk, 22 | stdout=self.stdout) 23 | 24 | # one has status set 25 | self.assertEqual(self.device1.powerstatus_set.count(), 1) 26 | self.assertEqual(self.device2.powerstatus_set.count(), 0) 27 | 28 | 29 | class TestPullAttributes(TestCase): 30 | def setUp(self): 31 | self.device1 = Device.objects.create(manufacturer_id=1) 32 | self.device2 = Device.objects.create(manufacturer_id=2) 33 | 34 | self.stdout = StringIO() 35 | 36 | @patch('django_iot.apps.interactions.tasks.client.get_attributes') 37 | def test_pull_one(self, mock_method): 38 | mock_method.return_value = {'dummy': 15} 39 | # call command for one 40 | call_command('interact', 'pull_attributes', 41 | device_id=self.device1.pk, 42 | stdout=self.stdout) 43 | 44 | # one has status set 45 | self.assertEqual(self.device1.attribute_set.count(), 1) 46 | self.assertEqual(self.device2.attribute_set.count(), 0) 47 | 48 | 49 | class TestSetStatus(TestCase): 50 | def setUp(self): 51 | self.device1 = Device.objects.create(manufacturer_id=1) 52 | self.device2 = Device.objects.create(manufacturer_id=2) 53 | 54 | self.stdout = StringIO() 55 | 56 | @patch('django_iot.apps.interactions.tasks.client.set_status') 57 | def test_set_one(self, mock_method): 58 | mock_method.return_value = { 59 | 'id': self.device1.pk, 60 | 'status': 'ok', 61 | } 62 | 63 | # call command for one 64 | call_command('interact', 'set_status', 65 | device_id=self.device1.pk, 66 | is_on='dummy', 67 | stdout=self.stdout) 68 | 69 | # one has status set 70 | self.assertEqual(self.device1.powerstatus_set.count(), 1) 71 | self.assertEqual(self.device2.powerstatus_set.count(), 0) 72 | 73 | # status has message 74 | self.assertEqual(self.device1.powerstatus_set.first().is_on, True) 75 | 76 | 77 | class TestSetAttributes(TestCase): 78 | def setUp(self): 79 | self.device1 = Device.objects.create(manufacturer_id=1) 80 | self.device2 = Device.objects.create(manufacturer_id=2) 81 | 82 | self.stdout = StringIO() 83 | 84 | @patch('django_iot.apps.interactions.tasks.client.set_color') 85 | @patch('django_iot.apps.interactions.tasks.client.get_attributes') 86 | def test_set_one(self, mock_get, mock_set): 87 | mock_set.return_value = { 88 | 'id': self.device1.pk, 89 | 'status': 'ok', 90 | } 91 | mock_get.return_value = {'dummy': 10} 92 | 93 | # call command for one 94 | call_command('interact', 'set_attributes', 95 | device_id=self.device1.pk, 96 | color='dummy', 97 | brightness=0.5, 98 | stdout=self.stdout) 99 | 100 | # one has status set 101 | self.assertEqual(self.device1.attribute_set.count(), 1) 102 | self.assertEqual(self.device2.attribute_set.count(), 0) 103 | 104 | # status has message 105 | self.assertEqual(self.device1.attribute_set.first().units, 'dummy') 106 | 107 | 108 | class TestTwitterVote(TestCase): 109 | def setUp(self): 110 | self.device1 = Device.objects.create(manufacturer_id=1) 111 | self.device2 = Device.objects.create(manufacturer_id=2) 112 | 113 | self.stdout = StringIO() 114 | 115 | @patch('django_iot.apps.interactions.tasks.client.set_color') 116 | @patch('django_iot.apps.interactions.tasks.client.get_attributes') 117 | def test_set_one(self, mock_get, mock_set): 118 | mock_set.return_value = { 119 | 'id': self.device1.pk, 120 | 'status': 'ok', 121 | } 122 | mock_get.return_value = {'dummy': 10} 123 | 124 | # call command for one 125 | call_command('interact', 'run_twitter_vote', 126 | device_id=self.device1.pk, 127 | hashtag='dummy', 128 | votechoices='red,blue,yellow', 129 | stdout=self.stdout) 130 | 131 | # one has status set 132 | self.assertEqual(self.device1.attribute_set.count(), 1) 133 | self.assertEqual(self.device2.attribute_set.count(), 0) 134 | 135 | # status has message 136 | self.assertEqual(self.device1.attribute_set.first().units, 'dummy') 137 | -------------------------------------------------------------------------------- /django_iot/apps/interactions/tests/test_tasks.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/apps/interactions/tests/test_tasks.py -------------------------------------------------------------------------------- /django_iot/apps/interactions/views.py: -------------------------------------------------------------------------------- 1 | from django.shortcuts import render 2 | from django.core.exceptions import ObjectDoesNotExist 3 | from django_iot.apps.devices.models import Device 4 | from django_iot.apps.interactions.models import TwitterVote 5 | from django_iot.apps.lifx import colors 6 | import os 7 | 8 | 9 | def home(request): 10 | # set up context 11 | context = { 12 | 'devices': [], 13 | 'vote': None, 14 | 'vote_info': { 15 | 'choices': TwitterVote.VOTE_CHOICE_LIST, 16 | 'hashtag': os.environ.get('VOTE_HASHTAG'), 17 | } 18 | } 19 | 20 | # collect info for devices 21 | for device in Device.objects.all(): 22 | # basic data 23 | device_data = { 24 | 'name': device.name, 25 | 'location': device.location, 26 | } 27 | 28 | # current status 29 | try: 30 | current_status = device.powerstatus_set.latest('valid_at') 31 | if current_status.is_on: 32 | device_data['status_message'] = 'on' 33 | else: 34 | device_data['status_message'] = 'off' 35 | device_data['status_time'] = current_status.valid_at 36 | except ObjectDoesNotExist: 37 | device_data['status_message'] = '[unknown]' 38 | device_data['status_time'] = None 39 | 40 | # current attributes 41 | try: 42 | current_hue = device.attribute_set.filter(units='hue').latest('valid_at') 43 | device_data['color_name'] = colors.hue_to_color_name(current_hue.value) 44 | device_data['color_hex'] = colors.NAME_TO_HEX[device_data['color_name']] 45 | device_data['color_time'] = current_hue.valid_at 46 | except ObjectDoesNotExist: 47 | device_data['hexcolor'] = '[unknown]' 48 | device_data['color_time'] = None 49 | 50 | # current brightness 51 | try: 52 | current_brightness = device.attribute_set.filter(units='brightness').latest('valid_at') 53 | device_data['brightness'] = int(current_brightness.value * 100) 54 | device_data['brightness_time'] = current_brightness.valid_at 55 | except ObjectDoesNotExist: 56 | device_data['brightness'] = '[unknown]' 57 | device_data['brightness_time'] = None 58 | 59 | # add to storage 60 | context['devices'].append(device_data) 61 | 62 | # latest vote 63 | try: 64 | current_vote = TwitterVote.objects.latest('created_at') 65 | tally_count_list = [int(v) for v in current_vote.tally.split(',')] 66 | unsorted_tallies = zip(current_vote.VOTE_CHOICE_LIST, tally_count_list) 67 | context['vote'] = { 68 | 'tallies': reversed(sorted(unsorted_tallies, key=lambda x: x[1])), 69 | 'log': current_vote.log.split(current_vote.LOG_LINE_SEP), 70 | } 71 | except ObjectDoesNotExist: 72 | pass 73 | 74 | # return 75 | return render(request, 'index.html', context) 76 | -------------------------------------------------------------------------------- /django_iot/apps/lifx/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/apps/lifx/__init__.py -------------------------------------------------------------------------------- /django_iot/apps/lifx/client.py: -------------------------------------------------------------------------------- 1 | from django_iot.apps.devices.models import Device 2 | from os import environ 3 | import requests 4 | 5 | 6 | HEADERS = { 7 | 'Authorization': 'Bearer %s' % environ.get('LIFX_TOKEN'), 8 | } 9 | 10 | BASE_URL = 'https://api.lifx.com/v1/lights/' 11 | 12 | 13 | def configure_devices(): 14 | """ 15 | Create all available devices, 16 | and update existing ones with cuurent metadata 17 | """ 18 | # make request 19 | url = BASE_URL + 'all' 20 | response = requests.get(url, headers=HEADERS) 21 | 22 | # process 23 | results = [] 24 | for data in response.json(): 25 | # get or create 26 | device, created = Device.objects.get_or_create(manufacturer_id=data['id']) 27 | 28 | # update 29 | device.name = data['label'] 30 | device.location = data['location']['name'] 31 | device.device_type = 'LIFX' 32 | device.save() 33 | 34 | # log 35 | results.append((device.pk, created)) 36 | 37 | # return 38 | return results 39 | 40 | 41 | def make_request(url, method='get', data=None): 42 | # make and parse request 43 | response = getattr(requests, method)(url, data=data, headers=HEADERS) 44 | json_data = response.json() 45 | 46 | # error 47 | if 'error' in json_data: 48 | raise RuntimeError(json_data['error']) 49 | 50 | # return 51 | return json_data 52 | 53 | 54 | def get_attributes(device_pk): 55 | """Get dict of numerical attributes""" 56 | # make request 57 | selector = 'id:%s' % Device.objects.get(pk=device_pk).manufacturer_id 58 | url = BASE_URL + selector 59 | data = make_request(url)[0] 60 | 61 | # assemble result 62 | result = { 63 | 'brightness': data['brightness'], 64 | 'hue': data['color']['hue'], 65 | 'saturation': data['color']['saturation'], 66 | 'kelvin': data['color']['kelvin'], 67 | } 68 | 69 | # return 70 | return result 71 | 72 | 73 | def get_status(device_pk): 74 | """Returns 'on' or 'off' """ 75 | # make request 76 | selector = 'id:%s' % Device.objects.get(pk=device_pk).manufacturer_id 77 | url = BASE_URL + selector 78 | data = make_request(url)[0] 79 | 80 | # return 81 | return data['power'] 82 | 83 | 84 | def set_status(device_pk, payload): 85 | # make request 86 | selector = 'id:%s' % Device.objects.get(pk=device_pk).manufacturer_id 87 | url = BASE_URL + selector + '/state' 88 | data = make_request(url, method='put', data=payload) 89 | 90 | # return 91 | try: 92 | return data['results'][0] 93 | except KeyError: 94 | return data 95 | 96 | 97 | def breathe(device_pk, 98 | to_color, from_color=None, 99 | n_cycles=5, period_seconds=1): 100 | # set up payload 101 | payload = { 102 | 'color': to_color, 103 | 'cycles': n_cycles, 104 | 'period': period_seconds, 105 | } 106 | if from_color: 107 | payload['from_color'] = from_color 108 | 109 | # make request 110 | selector = 'id:%s' % Device.objects.get(pk=device_pk).manufacturer_id 111 | url = BASE_URL + selector + '/effects/breathe' 112 | data = make_request(url, method='post', data=payload) 113 | 114 | # return 115 | return data['results'][0] 116 | 117 | 118 | def turn_on(device_pk): 119 | payload = {'power': 'on'} 120 | return set_status(device_pk, payload) 121 | 122 | 123 | def turn_off(device_pk): 124 | payload = {'power': 'off'} 125 | return set_status(device_pk, payload) 126 | 127 | 128 | def set_color(device_pk, color=None, brightness=None): 129 | payload = {} 130 | if color: 131 | payload['color'] = color 132 | if brightness: 133 | payload['brightness'] = brightness 134 | return set_status(device_pk, payload) 135 | -------------------------------------------------------------------------------- /django_iot/apps/lifx/colors.py: -------------------------------------------------------------------------------- 1 | NAME_TO_HEX = { 2 | 'red': '#ff0000', 3 | 'orange': '#ff9900', 4 | 'yellow': '#ffff00', 5 | 'green': '#00ff00', 6 | 'cyan': '#00ffff', 7 | 'blue': '#0000ff', 8 | 'purple': '#9900ff', 9 | 'pink': '#ff00ff', 10 | } 11 | 12 | HUE_RANGE = { 13 | 'red': (0, 20), # expected 0 14 | 'orange': (20, 50), # expected 36 15 | 'yellow': (50, 100), # expected 60 16 | 'green': (100, 150), # expected 120 17 | 'cyan': (150, 220), # expected 180 18 | 'blue': (220, 270), # expected 250 19 | 'purple': (270, 300), # expected 280 20 | 'pink': (300, 400), # expected 325 21 | } 22 | 23 | 24 | def hue_to_color_name(hue): 25 | # check each hue range 26 | for name, (hue_min, hue_max) in HUE_RANGE.iteritems(): 27 | if hue >= hue_min and hue < hue_max: 28 | return name 29 | 30 | # if got here, no match 31 | raise ValueError('No color name found for hue %s' % hue) 32 | -------------------------------------------------------------------------------- /django_iot/apps/lifx/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | from django.conf import settings 3 | from unittest import skipIf 4 | from django_iot.apps.lifx import client 5 | from django_iot.apps.devices.models import Device 6 | 7 | 8 | class TestConfigure(TestCase): 9 | def test_configure_once(self): 10 | # no devices before 11 | self.assertEqual(Device.objects.count(), 0) 12 | 13 | # configure 14 | results = client.configure_devices() 15 | self.assertEqual(Device.objects.count(), 1) 16 | self.assertEqual(len(results), 1) 17 | self.assertEqual(results[0][0], Device.objects.first().pk) 18 | self.assertTrue(results[0][1]) 19 | 20 | def test_configure_twice(self): 21 | # configure twice 22 | client.configure_devices() 23 | results = client.configure_devices() 24 | 25 | # test only one created 26 | self.assertEqual(Device.objects.count(), 1) 27 | self.assertEqual(len(results), 1) 28 | self.assertEqual(results[0][0], Device.objects.first().pk) 29 | self.assertFalse(results[0][1]) 30 | 31 | 32 | class TestGetAttributes(TestCase): 33 | def setUp(self): 34 | client.configure_devices() 35 | self.device = Device.objects.first() 36 | 37 | def test_get(self): 38 | result = client.get_attributes(self.device.pk) 39 | self.assertItemsEqual(result.keys(), 40 | ['brightness', 'hue', 'saturation', 'kelvin']) 41 | 42 | 43 | class TestGetStatus(TestCase): 44 | def setUp(self): 45 | client.configure_devices() 46 | self.device = Device.objects.first() 47 | 48 | def test_get(self): 49 | result = client.get_status(self.device.pk) 50 | self.assertIn(result, ['on', 'off']) 51 | 52 | 53 | @skipIf(settings.SKIP_INTEGRATION_TESTS, 'integration tests') 54 | class TestSetStatus(TestCase): 55 | def setUp(self): 56 | client.configure_devices() 57 | self.device = Device.objects.first() 58 | 59 | def test_turn_on(self): 60 | result = client.turn_on(self.device.pk) 61 | self.assertEqual(result['id'], self.device.manufacturer_id) 62 | self.assertEqual(result['label'], self.device.name) 63 | self.assertEqual(result['status'], 'ok') 64 | 65 | def test_turn_off(self): 66 | result = client.turn_off(self.device.pk) 67 | self.assertEqual(result['id'], self.device.manufacturer_id) 68 | self.assertEqual(result['label'], self.device.name) 69 | self.assertEqual(result['status'], 'ok') 70 | 71 | def test_green(self): 72 | result = client.set_color(self.device.pk, color='green') 73 | self.assertEqual(result['id'], self.device.manufacturer_id) 74 | self.assertEqual(result['label'], self.device.name) 75 | self.assertEqual(result['status'], 'ok') 76 | 77 | def test_dim(self): 78 | result = client.set_color(self.device.pk, brightness=0.5) 79 | self.assertEqual(result['id'], self.device.manufacturer_id) 80 | self.assertEqual(result['label'], self.device.name) 81 | self.assertEqual(result['status'], 'ok') 82 | 83 | 84 | @skipIf(settings.SKIP_INTEGRATION_TESTS, 'integration tests') 85 | class TestEffects(TestCase): 86 | def setUp(self): 87 | client.configure_devices() 88 | self.device = Device.objects.first() 89 | 90 | def test_breathe(self): 91 | result = client.breathe( 92 | self.device.pk, 93 | to_color='blue', from_color='yellow', 94 | n_cycles=3, period_seconds=3, 95 | ) 96 | self.assertEqual(result['id'], self.device.manufacturer_id) 97 | self.assertEqual(result['label'], self.device.name) 98 | self.assertEqual(result['status'], 'ok') 99 | -------------------------------------------------------------------------------- /django_iot/apps/observations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/apps/observations/__init__.py -------------------------------------------------------------------------------- /django_iot/apps/observations/admin.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django_iot.apps.observations.models import Attribute, PowerStatus 3 | 4 | 5 | class AttributeAdmin(admin.ModelAdmin): 6 | list_display = ['valid_at', 'device', 'value', 'units'] 7 | 8 | 9 | class PowerStatusAdmin(admin.ModelAdmin): 10 | list_display = ['valid_at', 'device', 'is_on'] 11 | 12 | 13 | admin.site.register(Attribute, AttributeAdmin) 14 | admin.site.register(PowerStatus, PowerStatusAdmin) 15 | -------------------------------------------------------------------------------- /django_iot/apps/observations/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.4 on 2016-03-06 23:05 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | import django.db.models.deletion 7 | 8 | 9 | class Migration(migrations.Migration): 10 | 11 | initial = True 12 | 13 | dependencies = [ 14 | ('devices', '0002_device_manufacturer_id'), 15 | ] 16 | 17 | operations = [ 18 | migrations.CreateModel( 19 | name='Attribute', 20 | fields=[ 21 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 22 | ('created_at', models.DateTimeField(auto_now_add=True)), 23 | ('valid_at', models.DateTimeField(db_index=True)), 24 | ('value', models.FloatField()), 25 | ('units', models.CharField(db_index=True, max_length=10)), 26 | ('device', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='devices.Device')), 27 | ], 28 | options={ 29 | 'abstract': False, 30 | 'get_latest_by': 'valid_at', 31 | }, 32 | ), 33 | migrations.CreateModel( 34 | name='PowerStatus', 35 | fields=[ 36 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 37 | ('created_at', models.DateTimeField(auto_now_add=True)), 38 | ('valid_at', models.DateTimeField(db_index=True)), 39 | ('is_on', models.BooleanField()), 40 | ('device', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='devices.Device')), 41 | ], 42 | options={ 43 | 'abstract': False, 44 | 'get_latest_by': 'valid_at', 45 | }, 46 | ), 47 | ] 48 | -------------------------------------------------------------------------------- /django_iot/apps/observations/migrations/0002_color.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.2 on 2016-03-12 06:08 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations, models 6 | import django.db.models.deletion 7 | 8 | 9 | class Migration(migrations.Migration): 10 | 11 | dependencies = [ 12 | ('devices', '0002_device_manufacturer_id'), 13 | ('observations', '0001_initial'), 14 | ] 15 | 16 | operations = [ 17 | migrations.CreateModel( 18 | name='Color', 19 | fields=[ 20 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 21 | ('created_at', models.DateTimeField(auto_now_add=True)), 22 | ('valid_at', models.DateTimeField(db_index=True)), 23 | ('hex_string', models.CharField(max_length=7)), 24 | ('device', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='devices.Device')), 25 | ], 26 | options={ 27 | 'abstract': False, 28 | 'get_latest_by': 'valid_at', 29 | }, 30 | ), 31 | ] 32 | -------------------------------------------------------------------------------- /django_iot/apps/observations/migrations/0003_auto_20160326_2228.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9.2 on 2016-03-26 22:28 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | ('observations', '0002_color'), 12 | ] 13 | 14 | operations = [ 15 | migrations.RemoveField( 16 | model_name='color', 17 | name='device', 18 | ), 19 | migrations.DeleteModel( 20 | name='Color', 21 | ), 22 | ] 23 | -------------------------------------------------------------------------------- /django_iot/apps/observations/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/apps/observations/migrations/__init__.py -------------------------------------------------------------------------------- /django_iot/apps/observations/models.py: -------------------------------------------------------------------------------- 1 | from django.db import models 2 | 3 | 4 | class BaseAttribute(models.Model): 5 | # created 6 | created_at = models.DateTimeField(auto_now_add=True) 7 | 8 | # time that the attribute is valid 9 | # may be different than the time it was created 10 | # adding the index is important because it's used for sorting 11 | valid_at = models.DateTimeField(db_index=True) 12 | 13 | # device that's the source of the attribute 14 | device = models.ForeignKey('devices.Device') 15 | 16 | class Meta: 17 | abstract = True 18 | get_latest_by = 'valid_at' 19 | 20 | 21 | class Attribute(BaseAttribute): 22 | # numerical value of the attribute 23 | value = models.FloatField() 24 | 25 | # units of the numerical value 26 | # you may want to add choices to this 27 | # adding the index is important because it's used for filtering 28 | units = models.CharField(max_length=10, db_index=True) 29 | 30 | 31 | class PowerStatus(BaseAttribute): 32 | # true if on, false if off 33 | is_on = models.BooleanField() 34 | -------------------------------------------------------------------------------- /django_iot/apps/observations/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/apps/observations/tests/__init__.py -------------------------------------------------------------------------------- /django_iot/apps/observations/tests/test_models.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | from django.utils import timezone 3 | from django_iot.apps.devices.models import Device 4 | from django_iot.apps.observations.models import Attribute 5 | from datetime import timedelta 6 | 7 | 8 | class TestAttribute(TestCase): 9 | def setUp(self): 10 | # set up device 11 | self.device = Device.objects.create(name='my toi', 12 | device_type='TOI', 13 | location='robohome') 14 | 15 | def test_dates(self): 16 | # create observation in future 17 | obs = Attribute.objects.create( 18 | valid_at=timezone.now()+timedelta(hours=5), 19 | device=self.device, 20 | value=5, 21 | units='kW', 22 | ) 23 | 24 | # created and valid are different 25 | self.assertLess(obs.created_at, obs.valid_at) 26 | 27 | def test_latest_by(self): 28 | # set up observations going backward in time 29 | sample_time = timezone.now() 30 | for ihour in range(10): 31 | Attribute.objects.create( 32 | valid_at=sample_time-timedelta(hours=ihour), 33 | value=ihour*0.5, 34 | units='kW', 35 | device=self.device, 36 | ) 37 | 38 | # get latest and earliest 39 | latest = Attribute.objects.latest() 40 | earliest = Attribute.objects.earliest() 41 | 42 | # latest should have later valid_at but earlier created_at 43 | self.assertGreater(latest.valid_at, earliest.valid_at) 44 | self.assertLess(latest.created_at, earliest.created_at) 45 | 46 | def test_value_numeric(self): 47 | # raises ValueError when trying to cast string 'badvalue' to float 48 | self.assertRaises(ValueError, Attribute.objects.create, 49 | valid_at=timezone.now(), 50 | device=self.device, 51 | value='badvalue', 52 | units='goodunits') 53 | -------------------------------------------------------------------------------- /django_iot/celery.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | import os 3 | from django.conf import settings 4 | from celery import Celery 5 | 6 | # set the default Django settings module for the 'celery' program. 7 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_iot.settings.dev') 8 | app = Celery('django_iot') 9 | 10 | # Using a string here means the worker will not have to 11 | # pickle the object when using Windows. 12 | app.config_from_object('django.conf:settings') 13 | 14 | # autodiscover tasks in any app 15 | app.autodiscover_tasks(settings.INSTALLED_APPS) 16 | 17 | 18 | @app.task(bind=True) 19 | def debug_task(self): 20 | print('Request: {0!r}'.format(self.request)) 21 | 22 | 23 | # set schedule 24 | from django_iot.apps.interactions.schedule import SCHEDULE 25 | app.conf.CELERYBEAT_SCHEDULE = SCHEDULE 26 | -------------------------------------------------------------------------------- /django_iot/settings/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/settings/__init__.py -------------------------------------------------------------------------------- /django_iot/settings/common.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for django_iot project on Heroku. Fore more info, see: 3 | https://github.com/heroku/heroku-django-template 4 | 5 | For more information on this file, see 6 | https://docs.djangoproject.com/en/1.9/topics/settings/ 7 | 8 | For the full list of settings and their values, see 9 | https://docs.djangoproject.com/en/1.9/ref/settings/ 10 | """ 11 | 12 | import os 13 | import dj_database_url 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 17 | PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 18 | 19 | 20 | # Quick-start development settings - unsuitable for production 21 | # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ 22 | 23 | # SECURITY WARNING: keep the secret key used in production secret! 24 | SECRET_KEY = os.environ.get('SECRET_KEY') 25 | 26 | # SECURITY WARNING: don't run with debug turned on in production! 27 | DEBUG = False 28 | 29 | # Application definition 30 | 31 | INSTALLED_APPS = ( 32 | # django 33 | 'django.contrib.admin', 34 | 'django.contrib.auth', 35 | 'django.contrib.contenttypes', 36 | 'django.contrib.sessions', 37 | 'django.contrib.messages', 38 | 'django.contrib.staticfiles', 39 | 40 | # local apps 41 | 'django_iot.apps.devices', 42 | 'django_iot.apps.observations', 43 | 'django_iot.apps.interactions', 44 | ) 45 | 46 | MIDDLEWARE_CLASSES = ( 47 | 'django.contrib.sessions.middleware.SessionMiddleware', 48 | 'django.middleware.common.CommonMiddleware', 49 | 'django.middleware.csrf.CsrfViewMiddleware', 50 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 51 | 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 52 | 'django.contrib.messages.middleware.MessageMiddleware', 53 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 54 | 'django.middleware.security.SecurityMiddleware', 55 | ) 56 | 57 | ROOT_URLCONF = 'django_iot.urls' 58 | 59 | TEMPLATES = ( 60 | { 61 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 62 | 'DIRS': [os.path.join(PROJECT_ROOT, 'templates')], 63 | 'APP_DIRS': True, 64 | 'OPTIONS': { 65 | 'context_processors': [ 66 | 'django.template.context_processors.debug', 67 | 'django.template.context_processors.request', 68 | 'django.contrib.auth.context_processors.auth', 69 | 'django.contrib.messages.context_processors.messages', 70 | ], 71 | 'debug': DEBUG, 72 | }, 73 | }, 74 | ) 75 | 76 | WSGI_APPLICATION = 'django_iot.wsgi.application' 77 | 78 | 79 | # Database 80 | # https://docs.djangoproject.com/en/1.9/ref/settings/#databases 81 | 82 | DATABASES = { 83 | 'default': { 84 | 'ENGINE': 'django.db.backends.sqlite3', 85 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 86 | } 87 | } 88 | 89 | AUTH_PASSWORD_VALIDATORS = ( 90 | { 91 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 92 | }, 93 | { 94 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 95 | }, 96 | { 97 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 98 | }, 99 | { 100 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 101 | }, 102 | ) 103 | 104 | # Internationalization 105 | # https://docs.djangoproject.com/en/1.9/topics/i18n/ 106 | 107 | LANGUAGE_CODE = 'en-us' 108 | TIME_ZONE = 'UTC' 109 | USE_I18N = True 110 | USE_L10N = True 111 | USE_TZ = True 112 | 113 | # Update database configuration with $DATABASE_URL. 114 | db_from_env = dj_database_url.config() 115 | DATABASES['default'].update(db_from_env) 116 | 117 | # Honor the 'X-Forwarded-Proto' header for request.is_secure() 118 | SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') 119 | 120 | # Allow all host headers 121 | ALLOWED_HOSTS = ['*'] 122 | 123 | # Static files (CSS, JavaScript, Images) 124 | # https://docs.djangoproject.com/en/1.9/howto/static-files/ 125 | 126 | STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') 127 | STATIC_URL = '/static/' 128 | 129 | # Extra places for collectstatic to find static files. 130 | STATICFILES_DIRS = [ 131 | os.path.join(PROJECT_ROOT, 'static'), 132 | ] 133 | 134 | # Simplified static file serving. 135 | # https://warehouse.python.org/project/whitenoise/ 136 | STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' 137 | 138 | 139 | ########## CELERY CONFIGURATION 140 | # recommended settings: https://www.cloudamqp.com/docs/celery.html 141 | BROKER_POOL_LIMIT = 1 # Will decrease connection usage 142 | BROKER_HEARTBEAT = None # We're using TCP keep-alive instead 143 | BROKER_CONNECTION_TIMEOUT = 30 # May require a long timeout due to Linux DNS timeouts etc 144 | CELERY_RESULT_BACKEND = None # AMQP is not recommended as result backend as it creates thousands of queues 145 | CELERY_SEND_EVENTS = False # Will not create celeryev.* queues 146 | CELERY_EVENT_QUEUE_EXPIRES = 60 # Will delete all celeryev. queues without consumers after 1 minute. 147 | BROKER_URL = os.environ.get('CLOUDAMQP_URL', 'amqp://') 148 | ########## END CELERY CONFIGURATION 149 | -------------------------------------------------------------------------------- /django_iot/settings/dev.py: -------------------------------------------------------------------------------- 1 | from .common import * 2 | import os 3 | 4 | 5 | DEBUG = True 6 | 7 | # Skip integration tests by default. Usage: 8 | # from unittest import skipIf 9 | # @skipIf(settings.SKIP_INTEGRATION_TESTS) 10 | if os.environ.get('SKIP_INTEGRATION_TESTS', True): 11 | SKIP_INTEGRATION_TESTS = True 12 | else: 13 | SKIP_INTEGRATION_TESTS = False 14 | -------------------------------------------------------------------------------- /django_iot/settings/production.py: -------------------------------------------------------------------------------- 1 | from .common import * 2 | -------------------------------------------------------------------------------- /django_iot/static/humans.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aschn/django-iot/0b08143c36f70ff3a6e366de670cccc03f85d30b/django_iot/static/humans.txt -------------------------------------------------------------------------------- /django_iot/static/js/bootstrap.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap v3.3.6 (http://getbootstrap.com) 3 | * Copyright 2011-2015 Twitter, Inc. 4 | * Licensed under the MIT license 5 | */ 6 | if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>2)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.6",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.6",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.6",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.6",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.6",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.6",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.6",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.6",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); -------------------------------------------------------------------------------- /django_iot/templates/base.html: -------------------------------------------------------------------------------- 1 | {% load staticfiles %} 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | Django for IoT 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 31 | 32 |
33 | {% block content %} 34 | {% endblock %} 35 |
36 | 37 | 39 | 40 | 41 | 42 | {% block scripts %} 43 | {% endblock %} 44 | 45 | 46 | -------------------------------------------------------------------------------- /django_iot/templates/index.html: -------------------------------------------------------------------------------- 1 | {% extends 'base.html' %} 2 | {% load staticfiles %} 3 | 4 | {% block content %} 5 | 6 |
7 |
    8 | {% for device in devices %} 9 |
  • 10 |

    {{ device.name }} in {{ device.location }}

    11 |
    12 |
    power status
    13 |
    {{ device.status_message }} {{ device.status_time|timesince }} ago
    14 |
    color
    15 |
    {{ device.color_name }} {{ device.color_time|timesince }} ago
    16 |
    brightness
    17 |
    {{ device.brightness }}% {{ device.brightness_time|timesince }} ago
    18 |
    19 |
  • 20 | {% empty %} 21 |
  • ( no devices to show )
  • 22 | {% endfor %} 23 |
24 |
25 | 26 |
27 |
28 | {% if vote_info.hashtag %} 29 |

Tweet your vote with hashtag {{ vote_info.hashtag }}

30 |

Choices: {{ vote_info.choices|join:', ' }}

31 |

Example tweet: Muahaha imma vote twice {{ vote_info.choices|random }} {{ vote_info.choices|random }} {{ vote_info.hashtag }}

32 | {% else %} 33 |

Configure Twitter voting by setting environment variable VOTE_HASHTAG

34 | {% endif %} 35 |
36 |
37 | 38 | {% if vote %} 39 |
40 |
41 |
42 | {% for choice, n_votes in vote.tallies %} 43 |
{{choice}}
{{n_votes}}
44 | {% endfor %} 45 |
46 |
47 |
48 |
    49 | {% for line in vote.log %} 50 |
  • {{line|linebreaksbr}}
  • 51 | {% endfor %} 52 |
53 |
54 |
55 | {% endif %} 56 | 57 | {% endblock %} 58 | -------------------------------------------------------------------------------- /django_iot/urls.py: -------------------------------------------------------------------------------- 1 | """django_iot URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.8/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Add an import: from blog import urls as blog_urls 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) 15 | """ 16 | from django.conf.urls import include, url 17 | from django.contrib import admin 18 | from django_iot.apps.interactions.views import home 19 | 20 | 21 | urlpatterns = [ 22 | url(r'^admin/', include(admin.site.urls)), 23 | url(r'^$', home, name='home'), 24 | ] 25 | -------------------------------------------------------------------------------- /django_iot/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for django_iot project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/ 8 | """ 9 | 10 | 11 | import os 12 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_iot.settings.production") 13 | 14 | from django.core.wsgi import get_wsgi_application 15 | from whitenoise.django import DjangoWhiteNoise 16 | 17 | application = get_wsgi_application() 18 | application = DjangoWhiteNoise(application) 19 | -------------------------------------------------------------------------------- /manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_iot.settings.dev") 7 | 8 | from django.core.management import execute_from_command_line 9 | 10 | execute_from_command_line(sys.argv) 11 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | celery 2 | dj-database-url==0.4.0 3 | Django==1.9.2 4 | gunicorn==19.4.5 5 | mock 6 | psycopg2==2.6.1 7 | tweepy 8 | requests 9 | whitenoise==2.0.6 10 | -------------------------------------------------------------------------------- /runtime.txt: -------------------------------------------------------------------------------- 1 | python-2.7.11 --------------------------------------------------------------------------------